1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Lex/LiteralSupport.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaInternal.h"
39#include "clang/Sema/Template.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43#include <map>
44#include <set>
45
46using namespace clang;
47
48//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
52namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
58 class CheckDefaultArgumentVisitor
59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60 Expr *DefaultArg;
61 Sema *S;
62
63 public:
64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65 : DefaultArg(defarg), S(s) {}
66
67 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
69 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70 bool VisitLambdaExpr(LambdaExpr *Lambda);
71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72 };
73
74 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
77 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
79 return IsInvalid;
80 }
81
82 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86 NamedDecl *Decl = DRE->getDecl();
87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
96 return S->Diag(DRE->getBeginLoc(),
97 diag::err_param_default_argument_references_param)
98 << Param->getDeclName() << DefaultArg->getSourceRange();
99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
103 if (VDecl->isLocalVarDecl())
104 return S->Diag(DRE->getBeginLoc(),
105 diag::err_param_default_argument_references_local)
106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
107 }
108
109 return false;
110 }
111
112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
117 return S->Diag(ThisE->getBeginLoc(),
118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
120 }
121
122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?");
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
146 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
147 }
148}
149
150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
167 return;
168
169 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170 EST = EST_BasicNoexcept;
171
172 switch (EST) {
173 case EST_Unparsed:
174 case EST_Uninstantiated:
175 case EST_Unevaluated:
176 llvm_unreachable("should not see unresolved exception specs here");
177
178 // If this function can throw any exceptions, make a note of that.
179 case EST_MSAny:
180 case EST_None:
181 // FIXME: Whichever we see last of MSAny and None determines our result.
182 // We should make a consistent, order-independent choice here.
183 ClearExceptions();
184 ComputedEST = EST;
185 return;
186 case EST_NoexceptFalse:
187 ClearExceptions();
188 ComputedEST = EST_None;
189 return;
190 // FIXME: If the call to this decl is using any of its default arguments, we
191 // need to search them for potentially-throwing calls.
192 // If this function has a basic noexcept, it doesn't affect the outcome.
193 case EST_BasicNoexcept:
194 case EST_NoexceptTrue:
195 case EST_NoThrow:
196 return;
197 // If we're still at noexcept(true) and there's a throw() callee,
198 // change to that specification.
199 case EST_DynamicNone:
200 if (ComputedEST == EST_BasicNoexcept)
201 ComputedEST = EST_DynamicNone;
202 return;
203 case EST_DependentNoexcept:
204 llvm_unreachable(
205 "should not generate implicit declarations for dependent cases");
206 case EST_Dynamic:
207 break;
208 }
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216 Exceptions.push_back(E);
217}
218
219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220 if (!E || ComputedEST == EST_MSAny)
221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
244 if (Self->canThrow(E))
245 ComputedEST = EST_None;
246}
247
248bool
249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250 SourceLocation EqualLoc) {
251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269 if (Result.isInvalid())
270 return true;
271 Arg = Result.getAs<Expr>();
272
273 CheckCompletedExpr(Arg, EqualLoc);
274 Arg = MaybeCreateExprWithCleanups(Arg);
275
276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
278
279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
291 return false;
292}
293
294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
297void
298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
301 return;
302
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
304 UnparsedDefaultArgLocs.erase(Param);
305
306 // Default arguments are only permitted in C++
307 if (!getLangOpts().CPlusPlus) {
308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
310 Param->setInvalidDecl();
311 return;
312 }
313
314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
322 // parameter pack.
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
326 return;
327 }
328
329 // Check that the default argument is well-formed
330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
332 Param->setInvalidDecl();
333 return;
334 }
335
336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337}
338
339/// ActOnParamUnparsedDefaultArgument - We've seen a default
340/// argument for a function parameter, but we can't parse it yet
341/// because we're inside a class definition. Note that this default
342/// argument will be parsed later.
343void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
346 if (!param)
347 return;
348
349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
350 Param->setUnparsedDefaultArg();
351 UnparsedDefaultArgLocs[Param] = ArgLoc;
352}
353
354/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355/// the default argument for the parameter param failed.
356void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
358 if (!param)
359 return;
360
361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
362 Param->setInvalidDecl();
363 UnparsedDefaultArgLocs.erase(Param);
364 Param->setDefaultArg(new(Context)
365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
367 VK_RValue));
368}
369
370/// CheckExtraCXXDefaultArguments - Check for any extra default
371/// arguments in the declarator, which is not a function declaration
372/// or definition and therefore is not permitted to have default
373/// arguments. This routine should be invoked for every declarator
374/// that is not a function declaration or definition.
375void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
383 bool MightBeFunction = D.isFunctionDeclarationContext();
384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
390 // arguments.
391 MightBeFunction = false;
392 continue;
393 }
394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ++argIdx) {
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397 if (Param->hasUnparsedDefaultArg()) {
398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407 << SR;
408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
411 Param->setDefaultArg(nullptr);
412 }
413 }
414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
416 }
417 }
418}
419
420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
437 bool Invalid = false;
438
439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficient, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
474 // We found the right previous declaration.
475 break;
476 }
477
478 // C++ [dcl.fct.default]p4:
479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
490 //
491 // C++ [dcl.fct.default]p6:
492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
495 // member function declaration in the class definition.
496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
506 if (OldParamHasDfl && NewParamHasDfl) {
507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
513 if (getLangOpts().MicrosoftExt) {
514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524 Invalid = false;
525 }
526 }
527
528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
536 Diag(NewParam->getLocation(), DiagDefaultParamID)
537 << NewParam->getDefaultArgRange();
538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
543 Older = Older->getPreviousDecl();
544 OldParam = Older->getParamDecl(p);
545 }
546
547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
549 } else if (OldParamHasDfl) {
550 // Merge the old default argument into the new parameter unless the new
551 // function is a friend declaration in a template class. In the latter
552 // case the default arguments will be inherited when the friend
553 // declaration will be instantiated.
554 if (New->getFriendObjectKind() == Decl::FOK_None ||
555 !New->getLexicalDeclContext()->isDependentContext()) {
556 // It's important to use getInit() here; getDefaultArg()
557 // strips off any top-level ExprWithCleanups.
558 NewParam->setHasInheritedDefaultArg();
559 if (OldParam->hasUnparsedDefaultArg())
560 NewParam->setUnparsedDefaultArg();
561 else if (OldParam->hasUninstantiatedDefaultArg())
562 NewParam->setUninstantiatedDefaultArg(
563 OldParam->getUninstantiatedDefaultArg());
564 else
565 NewParam->setDefaultArg(OldParam->getInit());
566 }
567 } else if (NewParamHasDfl) {
568 if (New->getDescribedFunctionTemplate()) {
569 // Paragraph 4, quoted above, only applies to non-template functions.
570 Diag(NewParam->getLocation(),
571 diag::err_param_default_argument_template_redecl)
572 << NewParam->getDefaultArgRange();
573 Diag(PrevForDefaultArgs->getLocation(),
574 diag::note_template_prev_declaration)
575 << false;
576 } else if (New->getTemplateSpecializationKind()
577 != TSK_ImplicitInstantiation &&
578 New->getTemplateSpecializationKind() != TSK_Undeclared) {
579 // C++ [temp.expr.spec]p21:
580 // Default function arguments shall not be specified in a declaration
581 // or a definition for one of the following explicit specializations:
582 // - the explicit specialization of a function template;
583 // - the explicit specialization of a member function template;
584 // - the explicit specialization of a member function of a class
585 // template where the class template specialization to which the
586 // member function specialization belongs is implicitly
587 // instantiated.
588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590 << New->getDeclName()
591 << NewParam->getDefaultArgRange();
592 } else if (New->getDeclContext()->isDependentContext()) {
593 // C++ [dcl.fct.default]p6 (DR217):
594 // Default arguments for a member function of a class template shall
595 // be specified on the initial declaration of the member function
596 // within the class template.
597 //
598 // Reading the tea leaves a bit in DR217 and its reference to DR205
599 // leads me to the conclusion that one cannot add default function
600 // arguments for an out-of-line definition of a member function of a
601 // dependent type.
602 int WhichKind = 2;
603 if (CXXRecordDecl *Record
604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605 if (Record->getDescribedClassTemplate())
606 WhichKind = 0;
607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
608 WhichKind = 1;
609 else
610 WhichKind = 2;
611 }
612
613 Diag(NewParam->getLocation(),
614 diag::err_param_default_argument_member_template_redecl)
615 << WhichKind
616 << NewParam->getDefaultArgRange();
617 }
618 }
619 }
620
621 // DR1344: If a default argument is added outside a class definition and that
622 // default argument makes the function a special member function, the program
623 // is ill-formed. This can only happen for constructors.
624 if (isa<CXXConstructorDecl>(New) &&
625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628 if (NewSM != OldSM) {
629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630 assert(NewParam->hasDefaultArg());
631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632 << NewParam->getDefaultArgRange() << NewSM;
633 Diag(Old->getLocation(), diag::note_previous_declaration);
634 }
635 }
636
637 const FunctionDecl *Def;
638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639 // template has a constexpr specifier then all its declarations shall
640 // contain the constexpr specifier.
641 if (New->isConstexpr() != Old->isConstexpr()) {
642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643 << New << New->isConstexpr();
644 Diag(Old->getLocation(), diag::note_previous_declaration);
645 Invalid = true;
646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647 Old->isDefined(Def) &&
648 // If a friend function is inlined but does not have 'inline'
649 // specifier, it is a definition. Do not report attribute conflict
650 // in this case, redefinition will be diagnosed later.
651 (New->isInlineSpecified() ||
652 New->getFriendObjectKind() == Decl::FOK_None)) {
653 // C++11 [dcl.fcn.spec]p4:
654 // If the definition of a function appears in a translation unit before its
655 // first declaration as inline, the program is ill-formed.
656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657 Diag(Def->getLocation(), diag::note_previous_definition);
658 Invalid = true;
659 }
660
661 // C++17 [temp.deduct.guide]p3:
662 // Two deduction guide declarations in the same translation unit
663 // for the same class template shall not have equivalent
664 // parameter-declaration-clauses.
665 if (isa<CXXDeductionGuideDecl>(New) &&
666 !New->isFunctionTemplateSpecialization()) {
667 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668 Diag(Old->getLocation(), diag::note_previous_declaration);
669 }
670
671 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672 // argument expression, that declaration shall be a definition and shall be
673 // the only declaration of the function or function template in the
674 // translation unit.
675 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
676 functionDeclHasDefaultArgument(Old)) {
677 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678 Diag(Old->getLocation(), diag::note_previous_declaration);
679 Invalid = true;
680 }
681
682 return Invalid;
683}
684
685NamedDecl *
686Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
687 MultiTemplateParamsArg TemplateParamLists) {
688 assert(D.isDecompositionDeclarator());
689 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
690
691 // The syntax only allows a decomposition declarator as a simple-declaration,
692 // a for-range-declaration, or a condition in Clang, but we parse it in more
693 // cases than that.
694 if (!D.mayHaveDecompositionDeclarator()) {
695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696 << Decomp.getSourceRange();
697 return nullptr;
698 }
699
700 if (!TemplateParamLists.empty()) {
701 // FIXME: There's no rule against this, but there are also no rules that
702 // would actually make it usable, so we reject it for now.
703 Diag(TemplateParamLists.front()->getTemplateLoc(),
704 diag::err_decomp_decl_template);
705 return nullptr;
706 }
707
708 Diag(Decomp.getLSquareLoc(),
709 !getLangOpts().CPlusPlus17
710 ? diag::ext_decomp_decl
711 : D.getContext() == DeclaratorContext::ConditionContext
712 ? diag::ext_decomp_decl_cond
713 : diag::warn_cxx14_compat_decomp_decl)
714 << Decomp.getSourceRange();
715
716 // The semantic context is always just the current context.
717 DeclContext *const DC = CurContext;
718
719 // C++17 [dcl.dcl]/8:
720 // The decl-specifier-seq shall contain only the type-specifier auto
721 // and cv-qualifiers.
722 // C++2a [dcl.dcl]/8:
723 // If decl-specifier-seq contains any decl-specifier other than static,
724 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
725 auto &DS = D.getDeclSpec();
726 {
727 SmallVector<StringRef, 8> BadSpecifiers;
728 SmallVector<SourceLocation, 8> BadSpecifierLocs;
729 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731 if (auto SCS = DS.getStorageClassSpec()) {
732 if (SCS == DeclSpec::SCS_static) {
733 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
735 } else {
736 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
738 }
739 }
740 if (auto TSCS = DS.getThreadStorageClassSpec()) {
741 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
743 }
744 if (DS.isConstexprSpecified()) {
745 BadSpecifiers.push_back("constexpr");
746 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
747 }
748 if (DS.isInlineSpecified()) {
749 BadSpecifiers.push_back("inline");
750 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
751 }
752 if (!BadSpecifiers.empty()) {
753 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
754 Err << (int)BadSpecifiers.size()
755 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
756 // Don't add FixItHints to remove the specifiers; we do still respect
757 // them when building the underlying variable.
758 for (auto Loc : BadSpecifierLocs)
759 Err << SourceRange(Loc, Loc);
760 } else if (!CPlusPlus20Specifiers.empty()) {
761 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
762 getLangOpts().CPlusPlus2a
763 ? diag::warn_cxx17_compat_decomp_decl_spec
764 : diag::ext_decomp_decl_spec);
765 Warn << (int)CPlusPlus20Specifiers.size()
766 << llvm::join(CPlusPlus20Specifiers.begin(),
767 CPlusPlus20Specifiers.end(), " ");
768 for (auto Loc : CPlusPlus20SpecifierLocs)
769 Warn << SourceRange(Loc, Loc);
770 }
771 // We can't recover from it being declared as a typedef.
772 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
773 return nullptr;
774 }
775
776 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
777 QualType R = TInfo->getType();
778
779 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
780 UPPC_DeclarationType))
781 D.setInvalidType();
782
783 // The syntax only allows a single ref-qualifier prior to the decomposition
784 // declarator. No other declarator chunks are permitted. Also check the type
785 // specifier here.
786 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
787 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
788 (D.getNumTypeObjects() == 1 &&
789 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
790 Diag(Decomp.getLSquareLoc(),
791 (D.hasGroupingParens() ||
792 (D.getNumTypeObjects() &&
793 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
794 ? diag::err_decomp_decl_parens
795 : diag::err_decomp_decl_type)
796 << R;
797
798 // In most cases, there's no actual problem with an explicitly-specified
799 // type, but a function type won't work here, and ActOnVariableDeclarator
800 // shouldn't be called for such a type.
801 if (R->isFunctionType())
802 D.setInvalidType();
803 }
804
805 // Build the BindingDecls.
806 SmallVector<BindingDecl*, 8> Bindings;
807
808 // Build the BindingDecls.
809 for (auto &B : D.getDecompositionDeclarator().bindings()) {
810 // Check for name conflicts.
811 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
812 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
813 ForVisibleRedeclaration);
814 LookupName(Previous, S,
815 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
816
817 // It's not permitted to shadow a template parameter name.
818 if (Previous.isSingleResult() &&
819 Previous.getFoundDecl()->isTemplateParameter()) {
820 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
821 Previous.getFoundDecl());
822 Previous.clear();
823 }
824
825 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
826 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
827 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
828 /*AllowInlineNamespace*/false);
829 if (!Previous.empty()) {
830 auto *Old = Previous.getRepresentativeDecl();
831 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
832 Diag(Old->getLocation(), diag::note_previous_definition);
833 }
834
835 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
836 PushOnScopeChains(BD, S, true);
837 Bindings.push_back(BD);
838 ParsingInitForAutoVars.insert(BD);
839 }
840
841 // There are no prior lookup results for the variable itself, because it
842 // is unnamed.
843 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
844 Decomp.getLSquareLoc());
845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846 ForVisibleRedeclaration);
847
848 // Build the variable that holds the non-decomposed object.
849 bool AddToScope = true;
850 NamedDecl *New =
851 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
852 MultiTemplateParamsArg(), AddToScope, Bindings);
853 if (AddToScope) {
854 S->AddDecl(New);
855 CurContext->addHiddenDecl(New);
856 }
857
858 if (isInOpenMPDeclareTargetContext())
859 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
860
861 return New;
862}
863
864static bool checkSimpleDecomposition(
865 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
866 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
867 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
868 if ((int64_t)Bindings.size() != NumElems) {
869 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
870 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
871 << (NumElems < Bindings.size());
872 return true;
873 }
874
875 unsigned I = 0;
876 for (auto *B : Bindings) {
877 SourceLocation Loc = B->getLocation();
878 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
879 if (E.isInvalid())
880 return true;
881 E = GetInit(Loc, E.get(), I++);
882 if (E.isInvalid())
883 return true;
884 B->setBinding(ElemType, E.get());
885 }
886
887 return false;
888}
889
890static bool checkArrayLikeDecomposition(Sema &S,
891 ArrayRef<BindingDecl *> Bindings,
892 ValueDecl *Src, QualType DecompType,
893 const llvm::APSInt &NumElems,
894 QualType ElemType) {
895 return checkSimpleDecomposition(
896 S, Bindings, Src, DecompType, NumElems, ElemType,
897 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
898 ExprResult E = S.ActOnIntegerConstant(Loc, I);
899 if (E.isInvalid())
900 return ExprError();
901 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
902 });
903}
904
905static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
906 ValueDecl *Src, QualType DecompType,
907 const ConstantArrayType *CAT) {
908 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
909 llvm::APSInt(CAT->getSize()),
910 CAT->getElementType());
911}
912
913static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
914 ValueDecl *Src, QualType DecompType,
915 const VectorType *VT) {
916 return checkArrayLikeDecomposition(
917 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
918 S.Context.getQualifiedType(VT->getElementType(),
919 DecompType.getQualifiers()));
920}
921
922static bool checkComplexDecomposition(Sema &S,
923 ArrayRef<BindingDecl *> Bindings,
924 ValueDecl *Src, QualType DecompType,
925 const ComplexType *CT) {
926 return checkSimpleDecomposition(
927 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
928 S.Context.getQualifiedType(CT->getElementType(),
929 DecompType.getQualifiers()),
930 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
931 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
932 });
933}
934
935static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
936 TemplateArgumentListInfo &Args) {
937 SmallString<128> SS;
938 llvm::raw_svector_ostream OS(SS);
939 bool First = true;
940 for (auto &Arg : Args.arguments()) {
941 if (!First)
942 OS << ", ";
943 Arg.getArgument().print(PrintingPolicy, OS);
944 First = false;
945 }
946 return OS.str();
947}
948
949static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
950 SourceLocation Loc, StringRef Trait,
951 TemplateArgumentListInfo &Args,
952 unsigned DiagID) {
953 auto DiagnoseMissing = [&] {
954 if (DiagID)
955 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
956 Args);
957 return true;
958 };
959
960 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
961 NamespaceDecl *Std = S.getStdNamespace();
962 if (!Std)
963 return DiagnoseMissing();
964
965 // Look up the trait itself, within namespace std. We can diagnose various
966 // problems with this lookup even if we've been asked to not diagnose a
967 // missing specialization, because this can only fail if the user has been
968 // declaring their own names in namespace std or we don't support the
969 // standard library implementation in use.
970 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
971 Loc, Sema::LookupOrdinaryName);
972 if (!S.LookupQualifiedName(Result, Std))
973 return DiagnoseMissing();
974 if (Result.isAmbiguous())
975 return true;
976
977 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
978 if (!TraitTD) {
979 Result.suppressDiagnostics();
980 NamedDecl *Found = *Result.begin();
981 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
982 S.Diag(Found->getLocation(), diag::note_declared_at);
983 return true;
984 }
985
986 // Build the template-id.
987 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
988 if (TraitTy.isNull())
989 return true;
990 if (!S.isCompleteType(Loc, TraitTy)) {
991 if (DiagID)
992 S.RequireCompleteType(
993 Loc, TraitTy, DiagID,
994 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
995 return true;
996 }
997
998 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
999 assert(RD && "specialization of class template is not a class?");
1000
1001 // Look up the member of the trait type.
1002 S.LookupQualifiedName(TraitMemberLookup, RD);
1003 return TraitMemberLookup.isAmbiguous();
1004}
1005
1006static TemplateArgumentLoc
1007getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1008 uint64_t I) {
1009 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1010 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1011}
1012
1013static TemplateArgumentLoc
1014getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1015 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1016}
1017
1018namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1019
1020static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1021 llvm::APSInt &Size) {
1022 EnterExpressionEvaluationContext ContextRAII(
1023 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1024
1025 DeclarationName Value = S.PP.getIdentifierInfo("value");
1026 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1027
1028 // Form template argument list for tuple_size<T>.
1029 TemplateArgumentListInfo Args(Loc, Loc);
1030 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1031
1032 // If there's no tuple_size specialization, it's not tuple-like.
1033 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1034 return IsTupleLike::NotTupleLike;
1035
1036 // If we get this far, we've committed to the tuple interpretation, but
1037 // we can still fail if there actually isn't a usable ::value.
1038
1039 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1040 LookupResult &R;
1041 TemplateArgumentListInfo &Args;
1042 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1043 : R(R), Args(Args) {}
1044 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1045 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1046 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1047 }
1048 } Diagnoser(R, Args);
1049
1050 if (R.empty()) {
1051 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1052 return IsTupleLike::Error;
1053 }
1054
1055 ExprResult E =
1056 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1057 if (E.isInvalid())
1058 return IsTupleLike::Error;
1059
1060 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1061 if (E.isInvalid())
1062 return IsTupleLike::Error;
1063
1064 return IsTupleLike::TupleLike;
1065}
1066
1067/// \return std::tuple_element<I, T>::type.
1068static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1069 unsigned I, QualType T) {
1070 // Form template argument list for tuple_element<I, T>.
1071 TemplateArgumentListInfo Args(Loc, Loc);
1072 Args.addArgument(
1073 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1074 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1075
1076 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1077 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1078 if (lookupStdTypeTraitMember(
1079 S, R, Loc, "tuple_element", Args,
1080 diag::err_decomp_decl_std_tuple_element_not_specialized))
1081 return QualType();
1082
1083 auto *TD = R.getAsSingle<TypeDecl>();
1084 if (!TD) {
1085 R.suppressDiagnostics();
1086 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1087 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1088 if (!R.empty())
1089 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1090 return QualType();
1091 }
1092
1093 return S.Context.getTypeDeclType(TD);
1094}
1095
1096namespace {
1097struct BindingDiagnosticTrap {
1098 Sema &S;
1099 DiagnosticErrorTrap Trap;
1100 BindingDecl *BD;
1101
1102 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1103 : S(S), Trap(S.Diags), BD(BD) {}
1104 ~BindingDiagnosticTrap() {
1105 if (Trap.hasErrorOccurred())
1106 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1107 }
1108};
1109}
1110
1111static bool checkTupleLikeDecomposition(Sema &S,
1112 ArrayRef<BindingDecl *> Bindings,
1113 VarDecl *Src, QualType DecompType,
1114 const llvm::APSInt &TupleSize) {
1115 if ((int64_t)Bindings.size() != TupleSize) {
1116 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1117 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1118 << (TupleSize < Bindings.size());
1119 return true;
1120 }
1121
1122 if (Bindings.empty())
1123 return false;
1124
1125 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1126
1127 // [dcl.decomp]p3:
1128 // The unqualified-id get is looked up in the scope of E by class member
1129 // access lookup ...
1130 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1131 bool UseMemberGet = false;
1132 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1133 if (auto *RD = DecompType->getAsCXXRecordDecl())
1134 S.LookupQualifiedName(MemberGet, RD);
1135 if (MemberGet.isAmbiguous())
1136 return true;
1137 // ... and if that finds at least one declaration that is a function
1138 // template whose first template parameter is a non-type parameter ...
1139 for (NamedDecl *D : MemberGet) {
1140 if (FunctionTemplateDecl *FTD =
1141 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1142 TemplateParameterList *TPL = FTD->getTemplateParameters();
1143 if (TPL->size() != 0 &&
1144 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1145 // ... the initializer is e.get<i>().
1146 UseMemberGet = true;
1147 break;
1148 }
1149 }
1150 }
1151 }
1152
1153 unsigned I = 0;
1154 for (auto *B : Bindings) {
1155 BindingDiagnosticTrap Trap(S, B);
1156 SourceLocation Loc = B->getLocation();
1157
1158 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1159 if (E.isInvalid())
1160 return true;
1161
1162 // e is an lvalue if the type of the entity is an lvalue reference and
1163 // an xvalue otherwise
1164 if (!Src->getType()->isLValueReferenceType())
1165 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1166 E.get(), nullptr, VK_XValue);
1167
1168 TemplateArgumentListInfo Args(Loc, Loc);
1169 Args.addArgument(
1170 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1171
1172 if (UseMemberGet) {
1173 // if [lookup of member get] finds at least one declaration, the
1174 // initializer is e.get<i-1>().
1175 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1176 CXXScopeSpec(), SourceLocation(), nullptr,
1177 MemberGet, &Args, nullptr);
1178 if (E.isInvalid())
1179 return true;
1180
1181 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1182 } else {
1183 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1184 // in the associated namespaces.
1185 Expr *Get = UnresolvedLookupExpr::Create(
1186 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1187 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1188 UnresolvedSetIterator(), UnresolvedSetIterator());
1189
1190 Expr *Arg = E.get();
1191 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1192 }
1193 if (E.isInvalid())
1194 return true;
1195 Expr *Init = E.get();
1196
1197 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1198 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1199 if (T.isNull())
1200 return true;
1201
1202 // each vi is a variable of type "reference to T" initialized with the
1203 // initializer, where the reference is an lvalue reference if the
1204 // initializer is an lvalue and an rvalue reference otherwise
1205 QualType RefType =
1206 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1207 if (RefType.isNull())
1208 return true;
1209 auto *RefVD = VarDecl::Create(
1210 S.Context, Src->getDeclContext(), Loc, Loc,
1211 B->getDeclName().getAsIdentifierInfo(), RefType,
1212 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1213 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1214 RefVD->setTSCSpec(Src->getTSCSpec());
1215 RefVD->setImplicit();
1216 if (Src->isInlineSpecified())
1217 RefVD->setInlineSpecified();
1218 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1219
1220 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1221 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1222 InitializationSequence Seq(S, Entity, Kind, Init);
1223 E = Seq.Perform(S, Entity, Kind, Init);
1224 if (E.isInvalid())
1225 return true;
1226 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1227 if (E.isInvalid())
1228 return true;
1229 RefVD->setInit(E.get());
1230 RefVD->checkInitIsICE();
1231
1232 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1233 DeclarationNameInfo(B->getDeclName(), Loc),
1234 RefVD);
1235 if (E.isInvalid())
1236 return true;
1237
1238 B->setBinding(T, E.get());
1239 I++;
1240 }
1241
1242 return false;
1243}
1244
1245/// Find the base class to decompose in a built-in decomposition of a class type.
1246/// This base class search is, unfortunately, not quite like any other that we
1247/// perform anywhere else in C++.
1248static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1249 const CXXRecordDecl *RD,
1250 CXXCastPath &BasePath) {
1251 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1252 CXXBasePath &Path) {
1253 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1254 };
1255
1256 const CXXRecordDecl *ClassWithFields = nullptr;
1257 AccessSpecifier AS = AS_public;
1258 if (RD->hasDirectFields())
1259 // [dcl.decomp]p4:
1260 // Otherwise, all of E's non-static data members shall be public direct
1261 // members of E ...
1262 ClassWithFields = RD;
1263 else {
1264 // ... or of ...
1265 CXXBasePaths Paths;
1266 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1267 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1268 // If no classes have fields, just decompose RD itself. (This will work
1269 // if and only if zero bindings were provided.)
1270 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1271 }
1272
1273 CXXBasePath *BestPath = nullptr;
1274 for (auto &P : Paths) {
1275 if (!BestPath)
1276 BestPath = &P;
1277 else if (!S.Context.hasSameType(P.back().Base->getType(),
1278 BestPath->back().Base->getType())) {
1279 // ... the same ...
1280 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1281 << false << RD << BestPath->back().Base->getType()
1282 << P.back().Base->getType();
1283 return DeclAccessPair();
1284 } else if (P.Access < BestPath->Access) {
1285 BestPath = &P;
1286 }
1287 }
1288
1289 // ... unambiguous ...
1290 QualType BaseType = BestPath->back().Base->getType();
1291 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1292 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1293 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1294 return DeclAccessPair();
1295 }
1296
1297 // ... [accessible, implied by other rules] base class of E.
1298 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1299 *BestPath, diag::err_decomp_decl_inaccessible_base);
1300 AS = BestPath->Access;
1301
1302 ClassWithFields = BaseType->getAsCXXRecordDecl();
1303 S.BuildBasePathArray(Paths, BasePath);
1304 }
1305
1306 // The above search did not check whether the selected class itself has base
1307 // classes with fields, so check that now.
1308 CXXBasePaths Paths;
1309 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1310 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1311 << (ClassWithFields == RD) << RD << ClassWithFields
1312 << Paths.front().back().Base->getType();
1313 return DeclAccessPair();
1314 }
1315
1316 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1317}
1318
1319static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1320 ValueDecl *Src, QualType DecompType,
1321 const CXXRecordDecl *OrigRD) {
1322 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1323 diag::err_incomplete_type))
1324 return true;
1325
1326 CXXCastPath BasePath;
1327 DeclAccessPair BasePair =
1328 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1329 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1330 if (!RD)
1331 return true;
1332 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1333 DecompType.getQualifiers());
1334
1335 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1336 unsigned NumFields =
1337 std::count_if(RD->field_begin(), RD->field_end(),
1338 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1339 assert(Bindings.size() != NumFields);
1340 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1341 << DecompType << (unsigned)Bindings.size() << NumFields
1342 << (NumFields < Bindings.size());
1343 return true;
1344 };
1345
1346 // all of E's non-static data members shall be [...] well-formed
1347 // when named as e.name in the context of the structured binding,
1348 // E shall not have an anonymous union member, ...
1349 unsigned I = 0;
1350 for (auto *FD : RD->fields()) {
1351 if (FD->isUnnamedBitfield())
1352 continue;
1353
1354 if (FD->isAnonymousStructOrUnion()) {
1355 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1356 << DecompType << FD->getType()->isUnionType();
1357 S.Diag(FD->getLocation(), diag::note_declared_at);
1358 return true;
1359 }
1360
1361 // We have a real field to bind.
1362 if (I >= Bindings.size())
1363 return DiagnoseBadNumberOfBindings();
1364 auto *B = Bindings[I++];
1365 SourceLocation Loc = B->getLocation();
1366
1367 // The field must be accessible in the context of the structured binding.
1368 // We already checked that the base class is accessible.
1369 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1370 // const_cast here.
1371 S.CheckStructuredBindingMemberAccess(
1372 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1373 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1374 BasePair.getAccess(), FD->getAccess())));
1375
1376 // Initialize the binding to Src.FD.
1377 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1378 if (E.isInvalid())
1379 return true;
1380 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1381 VK_LValue, &BasePath);
1382 if (E.isInvalid())
1383 return true;
1384 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1385 CXXScopeSpec(), FD,
1386 DeclAccessPair::make(FD, FD->getAccess()),
1387 DeclarationNameInfo(FD->getDeclName(), Loc));
1388 if (E.isInvalid())
1389 return true;
1390
1391 // If the type of the member is T, the referenced type is cv T, where cv is
1392 // the cv-qualification of the decomposition expression.
1393 //
1394 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1395 // 'const' to the type of the field.
1396 Qualifiers Q = DecompType.getQualifiers();
1397 if (FD->isMutable())
1398 Q.removeConst();
1399 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1400 }
1401
1402 if (I != Bindings.size())
1403 return DiagnoseBadNumberOfBindings();
1404
1405 return false;
1406}
1407
1408void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1409 QualType DecompType = DD->getType();
1410
1411 // If the type of the decomposition is dependent, then so is the type of
1412 // each binding.
1413 if (DecompType->isDependentType()) {
1414 for (auto *B : DD->bindings())
1415 B->setType(Context.DependentTy);
1416 return;
1417 }
1418
1419 DecompType = DecompType.getNonReferenceType();
1420 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1421
1422 // C++1z [dcl.decomp]/2:
1423 // If E is an array type [...]
1424 // As an extension, we also support decomposition of built-in complex and
1425 // vector types.
1426 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1427 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1428 DD->setInvalidDecl();
1429 return;
1430 }
1431 if (auto *VT = DecompType->getAs<VectorType>()) {
1432 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1433 DD->setInvalidDecl();
1434 return;
1435 }
1436 if (auto *CT = DecompType->getAs<ComplexType>()) {
1437 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1438 DD->setInvalidDecl();
1439 return;
1440 }
1441
1442 // C++1z [dcl.decomp]/3:
1443 // if the expression std::tuple_size<E>::value is a well-formed integral
1444 // constant expression, [...]
1445 llvm::APSInt TupleSize(32);
1446 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1447 case IsTupleLike::Error:
1448 DD->setInvalidDecl();
1449 return;
1450
1451 case IsTupleLike::TupleLike:
1452 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1453 DD->setInvalidDecl();
1454 return;
1455
1456 case IsTupleLike::NotTupleLike:
1457 break;
1458 }
1459
1460 // C++1z [dcl.dcl]/8:
1461 // [E shall be of array or non-union class type]
1462 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1463 if (!RD || RD->isUnion()) {
1464 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1465 << DD << !RD << DecompType;
1466 DD->setInvalidDecl();
1467 return;
1468 }
1469
1470 // C++1z [dcl.decomp]/4:
1471 // all of E's non-static data members shall be [...] direct members of
1472 // E or of the same unambiguous public base class of E, ...
1473 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1474 DD->setInvalidDecl();
1475}
1476
1477/// Merge the exception specifications of two variable declarations.
1478///
1479/// This is called when there's a redeclaration of a VarDecl. The function
1480/// checks if the redeclaration might have an exception specification and
1481/// validates compatibility and merges the specs if necessary.
1482void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1483 // Shortcut if exceptions are disabled.
1484 if (!getLangOpts().CXXExceptions)
1485 return;
1486
1487 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1488 "Should only be called if types are otherwise the same.");
1489
1490 QualType NewType = New->getType();
1491 QualType OldType = Old->getType();
1492
1493 // We're only interested in pointers and references to functions, as well
1494 // as pointers to member functions.
1495 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1496 NewType = R->getPointeeType();
1497 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1498 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1499 NewType = P->getPointeeType();
1500 OldType = OldType->getAs<PointerType>()->getPointeeType();
1501 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1502 NewType = M->getPointeeType();
1503 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1504 }
1505
1506 if (!NewType->isFunctionProtoType())
1507 return;
1508
1509 // There's lots of special cases for functions. For function pointers, system
1510 // libraries are hopefully not as broken so that we don't need these
1511 // workarounds.
1512 if (CheckEquivalentExceptionSpec(
1513 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1514 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1515 New->setInvalidDecl();
1516 }
1517}
1518
1519/// CheckCXXDefaultArguments - Verify that the default arguments for a
1520/// function declaration are well-formed according to C++
1521/// [dcl.fct.default].
1522void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1523 unsigned NumParams = FD->getNumParams();
1524 unsigned p;
1525
1526 // Find first parameter with a default argument
1527 for (p = 0; p < NumParams; ++p) {
1528 ParmVarDecl *Param = FD->getParamDecl(p);
1529 if (Param->hasDefaultArg())
1530 break;
1531 }
1532
1533 // C++11 [dcl.fct.default]p4:
1534 // In a given function declaration, each parameter subsequent to a parameter
1535 // with a default argument shall have a default argument supplied in this or
1536 // a previous declaration or shall be a function parameter pack. A default
1537 // argument shall not be redefined by a later declaration (not even to the
1538 // same value).
1539 unsigned LastMissingDefaultArg = 0;
1540 for (; p < NumParams; ++p) {
1541 ParmVarDecl *Param = FD->getParamDecl(p);
1542 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1543 if (Param->isInvalidDecl())
1544 /* We already complained about this parameter. */;
1545 else if (Param->getIdentifier())
1546 Diag(Param->getLocation(),
1547 diag::err_param_default_argument_missing_name)
1548 << Param->getIdentifier();
1549 else
1550 Diag(Param->getLocation(),
1551 diag::err_param_default_argument_missing);
1552
1553 LastMissingDefaultArg = p;
1554 }
1555 }
1556
1557 if (LastMissingDefaultArg > 0) {
1558 // Some default arguments were missing. Clear out all of the
1559 // default arguments up to (and including) the last missing
1560 // default argument, so that we leave the function parameters
1561 // in a semantically valid state.
1562 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1563 ParmVarDecl *Param = FD->getParamDecl(p);
1564 if (Param->hasDefaultArg()) {
1565 Param->setDefaultArg(nullptr);
1566 }
1567 }
1568 }
1569}
1570
1571// CheckConstexprParameterTypes - Check whether a function's parameter types
1572// are all literal types. If so, return true. If not, produce a suitable
1573// diagnostic and return false.
1574static bool CheckConstexprParameterTypes(Sema &SemaRef,
1575 const FunctionDecl *FD) {
1576 unsigned ArgIndex = 0;
1577 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1578 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1579 e = FT->param_type_end();
1580 i != e; ++i, ++ArgIndex) {
1581 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1582 SourceLocation ParamLoc = PD->getLocation();
1583 if (!(*i)->isDependentType() &&
1584 SemaRef.RequireLiteralType(ParamLoc, *i,
1585 diag::err_constexpr_non_literal_param,
1586 ArgIndex+1, PD->getSourceRange(),
1587 isa<CXXConstructorDecl>(FD)))
1588 return false;
1589 }
1590 return true;
1591}
1592
1593/// Get diagnostic %select index for tag kind for
1594/// record diagnostic message.
1595/// WARNING: Indexes apply to particular diagnostics only!
1596///
1597/// \returns diagnostic %select index.
1598static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1599 switch (Tag) {
1600 case TTK_Struct: return 0;
1601 case TTK_Interface: return 1;
1602 case TTK_Class: return 2;
1603 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1604 }
1605}
1606
1607// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1608// the requirements of a constexpr function definition or a constexpr
1609// constructor definition. If so, return true. If not, produce appropriate
1610// diagnostics and return false.
1611//
1612// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1613bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1614 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1615 if (MD && MD->isInstance()) {
1616 // C++11 [dcl.constexpr]p4:
1617 // The definition of a constexpr constructor shall satisfy the following
1618 // constraints:
1619 // - the class shall not have any virtual base classes;
1620 //
1621 // FIXME: This only applies to constructors, not arbitrary member
1622 // functions.
1623 const CXXRecordDecl *RD = MD->getParent();
1624 if (RD->getNumVBases()) {
1625 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1626 << isa<CXXConstructorDecl>(NewFD)
1627 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1628 for (const auto &I : RD->vbases())
1629 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1630 << I.getSourceRange();
1631 return false;
1632 }
1633 }
1634
1635 if (!isa<CXXConstructorDecl>(NewFD)) {
1636 // C++11 [dcl.constexpr]p3:
1637 // The definition of a constexpr function shall satisfy the following
1638 // constraints:
1639 // - it shall not be virtual; (removed in C++20)
1640 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1641 if (Method && Method->isVirtual()) {
1642 if (getLangOpts().CPlusPlus2a) {
1643 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1644 } else {
1645 Method = Method->getCanonicalDecl();
1646 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1647
1648 // If it's not obvious why this function is virtual, find an overridden
1649 // function which uses the 'virtual' keyword.
1650 const CXXMethodDecl *WrittenVirtual = Method;
1651 while (!WrittenVirtual->isVirtualAsWritten())
1652 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1653 if (WrittenVirtual != Method)
1654 Diag(WrittenVirtual->getLocation(),
1655 diag::note_overridden_virtual_function);
1656 return false;
1657 }
1658 }
1659
1660 // - its return type shall be a literal type;
1661 QualType RT = NewFD->getReturnType();
1662 if (!RT->isDependentType() &&
1663 RequireLiteralType(NewFD->getLocation(), RT,
1664 diag::err_constexpr_non_literal_return))
1665 return false;
1666 }
1667
1668 // - each of its parameter types shall be a literal type;
1669 if (!CheckConstexprParameterTypes(*this, NewFD))
1670 return false;
1671
1672 return true;
1673}
1674
1675/// Check the given declaration statement is legal within a constexpr function
1676/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1677///
1678/// \return true if the body is OK (maybe only as an extension), false if we
1679/// have diagnosed a problem.
1680static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1681 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1682 // C++11 [dcl.constexpr]p3 and p4:
1683 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1684 // contain only
1685 for (const auto *DclIt : DS->decls()) {
1686 switch (DclIt->getKind()) {
1687 case Decl::StaticAssert:
1688 case Decl::Using:
1689 case Decl::UsingShadow:
1690 case Decl::UsingDirective:
1691 case Decl::UnresolvedUsingTypename:
1692 case Decl::UnresolvedUsingValue:
1693 // - static_assert-declarations
1694 // - using-declarations,
1695 // - using-directives,
1696 continue;
1697
1698 case Decl::Typedef:
1699 case Decl::TypeAlias: {
1700 // - typedef declarations and alias-declarations that do not define
1701 // classes or enumerations,
1702 const auto *TN = cast<TypedefNameDecl>(DclIt);
1703 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1704 // Don't allow variably-modified types in constexpr functions.
1705 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1706 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1707 << TL.getSourceRange() << TL.getType()
1708 << isa<CXXConstructorDecl>(Dcl);
1709 return false;
1710 }
1711 continue;
1712 }
1713
1714 case Decl::Enum:
1715 case Decl::CXXRecord:
1716 // C++1y allows types to be defined, not just declared.
1717 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1718 SemaRef.Diag(DS->getBeginLoc(),
1719 SemaRef.getLangOpts().CPlusPlus14
1720 ? diag::warn_cxx11_compat_constexpr_type_definition
1721 : diag::ext_constexpr_type_definition)
1722 << isa<CXXConstructorDecl>(Dcl);
1723 continue;
1724
1725 case Decl::EnumConstant:
1726 case Decl::IndirectField:
1727 case Decl::ParmVar:
1728 // These can only appear with other declarations which are banned in
1729 // C++11 and permitted in C++1y, so ignore them.
1730 continue;
1731
1732 case Decl::Var:
1733 case Decl::Decomposition: {
1734 // C++1y [dcl.constexpr]p3 allows anything except:
1735 // a definition of a variable of non-literal type or of static or
1736 // thread storage duration or for which no initialization is performed.
1737 const auto *VD = cast<VarDecl>(DclIt);
1738 if (VD->isThisDeclarationADefinition()) {
1739 if (VD->isStaticLocal()) {
1740 SemaRef.Diag(VD->getLocation(),
1741 diag::err_constexpr_local_var_static)
1742 << isa<CXXConstructorDecl>(Dcl)
1743 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1744 return false;
1745 }
1746 if (!VD->getType()->isDependentType() &&
1747 SemaRef.RequireLiteralType(
1748 VD->getLocation(), VD->getType(),
1749 diag::err_constexpr_local_var_non_literal_type,
1750 isa<CXXConstructorDecl>(Dcl)))
1751 return false;
1752 if (!VD->getType()->isDependentType() &&
1753 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1754 SemaRef.Diag(VD->getLocation(),
1755 diag::err_constexpr_local_var_no_init)
1756 << isa<CXXConstructorDecl>(Dcl);
1757 return false;
1758 }
1759 }
1760 SemaRef.Diag(VD->getLocation(),
1761 SemaRef.getLangOpts().CPlusPlus14
1762 ? diag::warn_cxx11_compat_constexpr_local_var
1763 : diag::ext_constexpr_local_var)
1764 << isa<CXXConstructorDecl>(Dcl);
1765 continue;
1766 }
1767
1768 case Decl::NamespaceAlias:
1769 case Decl::Function:
1770 // These are disallowed in C++11 and permitted in C++1y. Allow them
1771 // everywhere as an extension.
1772 if (!Cxx1yLoc.isValid())
1773 Cxx1yLoc = DS->getBeginLoc();
1774 continue;
1775
1776 default:
1777 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1778 << isa<CXXConstructorDecl>(Dcl);
1779 return false;
1780 }
1781 }
1782
1783 return true;
1784}
1785
1786/// Check that the given field is initialized within a constexpr constructor.
1787///
1788/// \param Dcl The constexpr constructor being checked.
1789/// \param Field The field being checked. This may be a member of an anonymous
1790/// struct or union nested within the class being checked.
1791/// \param Inits All declarations, including anonymous struct/union members and
1792/// indirect members, for which any initialization was provided.
1793/// \param Diagnosed Set to true if an error is produced.
1794static void CheckConstexprCtorInitializer(Sema &SemaRef,
1795 const FunctionDecl *Dcl,
1796 FieldDecl *Field,
1797 llvm::SmallSet<Decl*, 16> &Inits,
1798 bool &Diagnosed) {
1799 if (Field->isInvalidDecl())
1800 return;
1801
1802 if (Field->isUnnamedBitfield())
1803 return;
1804
1805 // Anonymous unions with no variant members and empty anonymous structs do not
1806 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1807 // indirect fields don't need initializing.
1808 if (Field->isAnonymousStructOrUnion() &&
1809 (Field->getType()->isUnionType()
1810 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1811 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1812 return;
1813
1814 if (!Inits.count(Field)) {
1815 if (!Diagnosed) {
1816 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1817 Diagnosed = true;
1818 }
1819 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1820 } else if (Field->isAnonymousStructOrUnion()) {
1821 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1822 for (auto *I : RD->fields())
1823 // If an anonymous union contains an anonymous struct of which any member
1824 // is initialized, all members must be initialized.
1825 if (!RD->isUnion() || Inits.count(I))
1826 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1827 }
1828}
1829
1830/// Check the provided statement is allowed in a constexpr function
1831/// definition.
1832static bool
1833CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1834 SmallVectorImpl<SourceLocation> &ReturnStmts,
1835 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1836 // - its function-body shall be [...] a compound-statement that contains only
1837 switch (S->getStmtClass()) {
1838 case Stmt::NullStmtClass:
1839 // - null statements,
1840 return true;
1841
1842 case Stmt::DeclStmtClass:
1843 // - static_assert-declarations
1844 // - using-declarations,
1845 // - using-directives,
1846 // - typedef declarations and alias-declarations that do not define
1847 // classes or enumerations,
1848 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1849 return false;
1850 return true;
1851
1852 case Stmt::ReturnStmtClass:
1853 // - and exactly one return statement;
1854 if (isa<CXXConstructorDecl>(Dcl)) {
1855 // C++1y allows return statements in constexpr constructors.
1856 if (!Cxx1yLoc.isValid())
1857 Cxx1yLoc = S->getBeginLoc();
1858 return true;
1859 }
1860
1861 ReturnStmts.push_back(S->getBeginLoc());
1862 return true;
1863
1864 case Stmt::CompoundStmtClass: {
1865 // C++1y allows compound-statements.
1866 if (!Cxx1yLoc.isValid())
1867 Cxx1yLoc = S->getBeginLoc();
1868
1869 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1870 for (auto *BodyIt : CompStmt->body()) {
1871 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1872 Cxx1yLoc, Cxx2aLoc))
1873 return false;
1874 }
1875 return true;
1876 }
1877
1878 case Stmt::AttributedStmtClass:
1879 if (!Cxx1yLoc.isValid())
1880 Cxx1yLoc = S->getBeginLoc();
1881 return true;
1882
1883 case Stmt::IfStmtClass: {
1884 // C++1y allows if-statements.
1885 if (!Cxx1yLoc.isValid())
1886 Cxx1yLoc = S->getBeginLoc();
1887
1888 IfStmt *If = cast<IfStmt>(S);
1889 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1890 Cxx1yLoc, Cxx2aLoc))
1891 return false;
1892 if (If->getElse() &&
1893 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1894 Cxx1yLoc, Cxx2aLoc))
1895 return false;
1896 return true;
1897 }
1898
1899 case Stmt::WhileStmtClass:
1900 case Stmt::DoStmtClass:
1901 case Stmt::ForStmtClass:
1902 case Stmt::CXXForRangeStmtClass:
1903 case Stmt::ContinueStmtClass:
1904 // C++1y allows all of these. We don't allow them as extensions in C++11,
1905 // because they don't make sense without variable mutation.
1906 if (!SemaRef.getLangOpts().CPlusPlus14)
1907 break;
1908 if (!Cxx1yLoc.isValid())
1909 Cxx1yLoc = S->getBeginLoc();
1910 for (Stmt *SubStmt : S->children())
1911 if (SubStmt &&
1912 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1913 Cxx1yLoc, Cxx2aLoc))
1914 return false;
1915 return true;
1916
1917 case Stmt::SwitchStmtClass:
1918 case Stmt::CaseStmtClass:
1919 case Stmt::DefaultStmtClass:
1920 case Stmt::BreakStmtClass:
1921 // C++1y allows switch-statements, and since they don't need variable
1922 // mutation, we can reasonably allow them in C++11 as an extension.
1923 if (!Cxx1yLoc.isValid())
1924 Cxx1yLoc = S->getBeginLoc();
1925 for (Stmt *SubStmt : S->children())
1926 if (SubStmt &&
1927 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1928 Cxx1yLoc, Cxx2aLoc))
1929 return false;
1930 return true;
1931
1932 case Stmt::CXXTryStmtClass:
1933 if (Cxx2aLoc.isInvalid())
1934 Cxx2aLoc = S->getBeginLoc();
1935 for (Stmt *SubStmt : S->children()) {
1936 if (SubStmt &&
1937 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1938 Cxx1yLoc, Cxx2aLoc))
1939 return false;
1940 }
1941 return true;
1942
1943 case Stmt::CXXCatchStmtClass:
1944 // Do not bother checking the language mode (already covered by the
1945 // try block check).
1946 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1947 cast<CXXCatchStmt>(S)->getHandlerBlock(),
1948 ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1949 return false;
1950 return true;
1951
1952 default:
1953 if (!isa<Expr>(S))
1954 break;
1955
1956 // C++1y allows expression-statements.
1957 if (!Cxx1yLoc.isValid())
1958 Cxx1yLoc = S->getBeginLoc();
1959 return true;
1960 }
1961
1962 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1963 << isa<CXXConstructorDecl>(Dcl);
1964 return false;
1965}
1966
1967/// Check the body for the given constexpr function declaration only contains
1968/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1969///
1970/// \return true if the body is OK, false if we have diagnosed a problem.
1971bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1972 SmallVector<SourceLocation, 4> ReturnStmts;
1973
1974 if (isa<CXXTryStmt>(Body)) {
1975 // C++11 [dcl.constexpr]p3:
1976 // The definition of a constexpr function shall satisfy the following
1977 // constraints: [...]
1978 // - its function-body shall be = delete, = default, or a
1979 // compound-statement
1980 //
1981 // C++11 [dcl.constexpr]p4:
1982 // In the definition of a constexpr constructor, [...]
1983 // - its function-body shall not be a function-try-block;
1984 //
1985 // This restriction is lifted in C++2a, as long as inner statements also
1986 // apply the general constexpr rules.
1987 Diag(Body->getBeginLoc(),
1988 !getLangOpts().CPlusPlus2a
1989 ? diag::ext_constexpr_function_try_block_cxx2a
1990 : diag::warn_cxx17_compat_constexpr_function_try_block)
1991 << isa<CXXConstructorDecl>(Dcl);
1992 }
1993
1994 // - its function-body shall be [...] a compound-statement that contains only
1995 // [... list of cases ...]
1996 //
1997 // Note that walking the children here is enough to properly check for
1998 // CompoundStmt and CXXTryStmt body.
1999 SourceLocation Cxx1yLoc, Cxx2aLoc;
2000 for (Stmt *SubStmt : Body->children()) {
2001 if (SubStmt &&
2002 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
2003 Cxx1yLoc, Cxx2aLoc))
2004 return false;
2005 }
2006
2007 if (Cxx2aLoc.isValid())
2008 Diag(Cxx2aLoc,
2009 getLangOpts().CPlusPlus2a
2010 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2011 : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2012 << isa<CXXConstructorDecl>(Dcl);
2013 if (Cxx1yLoc.isValid())
2014 Diag(Cxx1yLoc,
2015 getLangOpts().CPlusPlus14
2016 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2017 : diag::ext_constexpr_body_invalid_stmt)
2018 << isa<CXXConstructorDecl>(Dcl);
2019
2020 if (const CXXConstructorDecl *Constructor
2021 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2022 const CXXRecordDecl *RD = Constructor->getParent();
2023 // DR1359:
2024 // - every non-variant non-static data member and base class sub-object
2025 // shall be initialized;
2026 // DR1460:
2027 // - if the class is a union having variant members, exactly one of them
2028 // shall be initialized;
2029 if (RD->isUnion()) {
2030 if (Constructor->getNumCtorInitializers() == 0 &&
2031 RD->hasVariantMembers()) {
2032 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2033 return false;
2034 }
2035 } else if (!Constructor->isDependentContext() &&
2036 !Constructor->isDelegatingConstructor()) {
2037 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2038
2039 // Skip detailed checking if we have enough initializers, and we would
2040 // allow at most one initializer per member.
2041 bool AnyAnonStructUnionMembers = false;
2042 unsigned Fields = 0;
2043 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2044 E = RD->field_end(); I != E; ++I, ++Fields) {
2045 if (I->isAnonymousStructOrUnion()) {
2046 AnyAnonStructUnionMembers = true;
2047 break;
2048 }
2049 }
2050 // DR1460:
2051 // - if the class is a union-like class, but is not a union, for each of
2052 // its anonymous union members having variant members, exactly one of
2053 // them shall be initialized;
2054 if (AnyAnonStructUnionMembers ||
2055 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2056 // Check initialization of non-static data members. Base classes are
2057 // always initialized so do not need to be checked. Dependent bases
2058 // might not have initializers in the member initializer list.
2059 llvm::SmallSet<Decl*, 16> Inits;
2060 for (const auto *I: Constructor->inits()) {
2061 if (FieldDecl *FD = I->getMember())
2062 Inits.insert(FD);
2063 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2064 Inits.insert(ID->chain_begin(), ID->chain_end());
2065 }
2066
2067 bool Diagnosed = false;
2068 for (auto *I : RD->fields())
2069 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2070 if (Diagnosed)
2071 return false;
2072 }
2073 }
2074 } else {
2075 if (ReturnStmts.empty()) {
2076 // C++1y doesn't require constexpr functions to contain a 'return'
2077 // statement. We still do, unless the return type might be void, because
2078 // otherwise if there's no return statement, the function cannot
2079 // be used in a core constant expression.
2080 bool OK = getLangOpts().CPlusPlus14 &&
2081 (Dcl->getReturnType()->isVoidType() ||
2082 Dcl->getReturnType()->isDependentType());
2083 Diag(Dcl->getLocation(),
2084 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2085 : diag::err_constexpr_body_no_return);
2086 if (!OK)
2087 return false;
2088 } else if (ReturnStmts.size() > 1) {
2089 Diag(ReturnStmts.back(),
2090 getLangOpts().CPlusPlus14
2091 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2092 : diag::ext_constexpr_body_multiple_return);
2093 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2094 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2095 }
2096 }
2097
2098 // C++11 [dcl.constexpr]p5:
2099 // if no function argument values exist such that the function invocation
2100 // substitution would produce a constant expression, the program is
2101 // ill-formed; no diagnostic required.
2102 // C++11 [dcl.constexpr]p3:
2103 // - every constructor call and implicit conversion used in initializing the
2104 // return value shall be one of those allowed in a constant expression.
2105 // C++11 [dcl.constexpr]p4:
2106 // - every constructor involved in initializing non-static data members and
2107 // base class sub-objects shall be a constexpr constructor.
2108 SmallVector<PartialDiagnosticAt, 8> Diags;
2109 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2110 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2111 << isa<CXXConstructorDecl>(Dcl);
2112 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2113 Diag(Diags[I].first, Diags[I].second);
2114 // Don't return false here: we allow this for compatibility in
2115 // system headers.
2116 }
2117
2118 return true;
2119}
2120
2121/// Get the class that is directly named by the current context. This is the
2122/// class for which an unqualified-id in this scope could name a constructor
2123/// or destructor.
2124///
2125/// If the scope specifier denotes a class, this will be that class.
2126/// If the scope specifier is empty, this will be the class whose
2127/// member-specification we are currently within. Otherwise, there
2128/// is no such class.
2129CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2130 assert(getLangOpts().CPlusPlus && "No class names in C!");
2131
2132 if (SS && SS->isInvalid())
2133 return nullptr;
2134
2135 if (SS && SS->isNotEmpty()) {
2136 DeclContext *DC = computeDeclContext(*SS, true);
2137 return dyn_cast_or_null<CXXRecordDecl>(DC);
2138 }
2139
2140 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2141}
2142
2143/// isCurrentClassName - Determine whether the identifier II is the
2144/// name of the class type currently being defined. In the case of
2145/// nested classes, this will only return true if II is the name of
2146/// the innermost class.
2147bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2148 const CXXScopeSpec *SS) {
2149 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2150 return CurDecl && &II == CurDecl->getIdentifier();
2151}
2152
2153/// Determine whether the identifier II is a typo for the name of
2154/// the class type currently being defined. If so, update it to the identifier
2155/// that should have been used.
2156bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2157 assert(getLangOpts().CPlusPlus && "No class names in C!");
2158
2159 if (!getLangOpts().SpellChecking)
2160 return false;
2161
2162 CXXRecordDecl *CurDecl;
2163 if (SS && SS->isSet() && !SS->isInvalid()) {
2164 DeclContext *DC = computeDeclContext(*SS, true);
2165 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2166 } else
2167 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2168
2169 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2170 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2171 < II->getLength()) {
2172 II = CurDecl->getIdentifier();
2173 return true;
2174 }
2175
2176 return false;
2177}
2178
2179/// Determine whether the given class is a base class of the given
2180/// class, including looking at dependent bases.
2181static bool findCircularInheritance(const CXXRecordDecl *Class,
2182 const CXXRecordDecl *Current) {
2183 SmallVector<const CXXRecordDecl*, 8> Queue;
2184
2185 Class = Class->getCanonicalDecl();
2186 while (true) {
2187 for (const auto &I : Current->bases()) {
2188 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2189 if (!Base)
2190 continue;
2191
2192 Base = Base->getDefinition();
2193 if (!Base)
2194 continue;
2195
2196 if (Base->getCanonicalDecl() == Class)
2197 return true;
2198
2199 Queue.push_back(Base);
2200 }
2201
2202 if (Queue.empty())
2203 return false;
2204
2205 Current = Queue.pop_back_val();
2206 }
2207
2208 return false;
2209}
2210
2211/// Check the validity of a C++ base class specifier.
2212///
2213/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2214/// and returns NULL otherwise.
2215CXXBaseSpecifier *
2216Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2217 SourceRange SpecifierRange,
2218 bool Virtual, AccessSpecifier Access,
2219 TypeSourceInfo *TInfo,
2220 SourceLocation EllipsisLoc) {
2221 QualType BaseType = TInfo->getType();
2222
2223 // C++ [class.union]p1:
2224 // A union shall not have base classes.
2225 if (Class->isUnion()) {
2226 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2227 << SpecifierRange;
2228 return nullptr;
2229 }
2230
2231 if (EllipsisLoc.isValid() &&
2232 !TInfo->getType()->containsUnexpandedParameterPack()) {
2233 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2234 << TInfo->getTypeLoc().getSourceRange();
2235 EllipsisLoc = SourceLocation();
2236 }
2237
2238 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2239
2240 if (BaseType->isDependentType()) {
2241 // Make sure that we don't have circular inheritance among our dependent
2242 // bases. For non-dependent bases, the check for completeness below handles
2243 // this.
2244 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2245 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2246 ((BaseDecl = BaseDecl->getDefinition()) &&
2247 findCircularInheritance(Class, BaseDecl))) {
2248 Diag(BaseLoc, diag::err_circular_inheritance)
2249 << BaseType << Context.getTypeDeclType(Class);
2250
2251 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2252 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2253 << BaseType;
2254
2255 return nullptr;
2256 }
2257 }
2258
2259 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2260 Class->getTagKind() == TTK_Class,
2261 Access, TInfo, EllipsisLoc);
2262 }
2263
2264 // Base specifiers must be record types.
2265 if (!BaseType->isRecordType()) {
2266 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2267 return nullptr;
2268 }
2269
2270 // C++ [class.union]p1:
2271 // A union shall not be used as a base class.
2272 if (BaseType->isUnionType()) {
2273 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2274 return nullptr;
2275 }
2276
2277 // For the MS ABI, propagate DLL attributes to base class templates.
2278 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2279 if (Attr *ClassAttr = getDLLAttr(Class)) {
2280 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2281 BaseType->getAsCXXRecordDecl())) {
2282 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2283 BaseLoc);
2284 }
2285 }
2286 }
2287
2288 // C++ [class.derived]p2:
2289 // The class-name in a base-specifier shall not be an incompletely
2290 // defined class.
2291 if (RequireCompleteType(BaseLoc, BaseType,
2292 diag::err_incomplete_base_class, SpecifierRange)) {
2293 Class->setInvalidDecl();
2294 return nullptr;
2295 }
2296
2297 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2298 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2299 assert(BaseDecl && "Record type has no declaration");
2300 BaseDecl = BaseDecl->getDefinition();
2301 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2302 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2303 assert(CXXBaseDecl && "Base type is not a C++ type");
2304
2305 // Microsoft docs say:
2306 // "If a base-class has a code_seg attribute, derived classes must have the
2307 // same attribute."
2308 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2309 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2310 if ((DerivedCSA || BaseCSA) &&
2311 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2312 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2313 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2314 << CXXBaseDecl;
2315 return nullptr;
2316 }
2317
2318 // A class which contains a flexible array member is not suitable for use as a
2319 // base class:
2320 // - If the layout determines that a base comes before another base,
2321 // the flexible array member would index into the subsequent base.
2322 // - If the layout determines that base comes before the derived class,
2323 // the flexible array member would index into the derived class.
2324 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2325 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2326 << CXXBaseDecl->getDeclName();
2327 return nullptr;
2328 }
2329
2330 // C++ [class]p3:
2331 // If a class is marked final and it appears as a base-type-specifier in
2332 // base-clause, the program is ill-formed.
2333 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2334 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2335 << CXXBaseDecl->getDeclName()
2336 << FA->isSpelledAsSealed();
2337 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2338 << CXXBaseDecl->getDeclName() << FA->getRange();
2339 return nullptr;
2340 }
2341
2342 if (BaseDecl->isInvalidDecl())
2343 Class->setInvalidDecl();
2344
2345 // Create the base specifier.
2346 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2347 Class->getTagKind() == TTK_Class,
2348 Access, TInfo, EllipsisLoc);
2349}
2350
2351/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2352/// one entry in the base class list of a class specifier, for
2353/// example:
2354/// class foo : public bar, virtual private baz {
2355/// 'public bar' and 'virtual private baz' are each base-specifiers.
2356BaseResult
2357Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2358 ParsedAttributes &Attributes,
2359 bool Virtual, AccessSpecifier Access,
2360 ParsedType basetype, SourceLocation BaseLoc,
2361 SourceLocation EllipsisLoc) {
2362 if (!classdecl)
2363 return true;
2364
2365 AdjustDeclIfTemplate(classdecl);
2366 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2367 if (!Class)
2368 return true;
2369
2370 // We haven't yet attached the base specifiers.
2371 Class->setIsParsingBaseSpecifiers();
2372
2373 // We do not support any C++11 attributes on base-specifiers yet.
2374 // Diagnose any attributes we see.
2375 for (const ParsedAttr &AL : Attributes) {
2376 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2377 continue;
2378 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2379 ? (unsigned)diag::warn_unknown_attribute_ignored
2380 : (unsigned)diag::err_base_specifier_attribute)
2381 << AL.getName();
2382 }
2383
2384 TypeSourceInfo *TInfo = nullptr;
2385 GetTypeFromParser(basetype, &TInfo);
2386
2387 if (EllipsisLoc.isInvalid() &&
2388 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2389 UPPC_BaseType))
2390 return true;
2391
2392 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2393 Virtual, Access, TInfo,
2394 EllipsisLoc))
2395 return BaseSpec;
2396 else
2397 Class->setInvalidDecl();
2398
2399 return true;
2400}
2401
2402/// Use small set to collect indirect bases. As this is only used
2403/// locally, there's no need to abstract the small size parameter.
2404typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2405
2406/// Recursively add the bases of Type. Don't add Type itself.
2407static void
2408NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2409 const QualType &Type)
2410{
2411 // Even though the incoming type is a base, it might not be
2412 // a class -- it could be a template parm, for instance.
2413 if (auto Rec = Type->getAs<RecordType>()) {
2414 auto Decl = Rec->getAsCXXRecordDecl();
2415
2416 // Iterate over its bases.
2417 for (const auto &BaseSpec : Decl->bases()) {
2418 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2419 .getUnqualifiedType();
2420 if (Set.insert(Base).second)
2421 // If we've not already seen it, recurse.
2422 NoteIndirectBases(Context, Set, Base);
2423 }
2424 }
2425}
2426
2427/// Performs the actual work of attaching the given base class
2428/// specifiers to a C++ class.
2429bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2430 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2431 if (Bases.empty())
2432 return false;
2433
2434 // Used to keep track of which base types we have already seen, so
2435 // that we can properly diagnose redundant direct base types. Note
2436 // that the key is always the unqualified canonical type of the base
2437 // class.
2438 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2439
2440 // Used to track indirect bases so we can see if a direct base is
2441 // ambiguous.
2442 IndirectBaseSet IndirectBaseTypes;
2443
2444 // Copy non-redundant base specifiers into permanent storage.
2445 unsigned NumGoodBases = 0;
2446 bool Invalid = false;
2447 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2448 QualType NewBaseType
2449 = Context.getCanonicalType(Bases[idx]->getType());
2450 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2451
2452 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2453 if (KnownBase) {
2454 // C++ [class.mi]p3:
2455 // A class shall not be specified as a direct base class of a
2456 // derived class more than once.
2457 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2458 << KnownBase->getType() << Bases[idx]->getSourceRange();
2459
2460 // Delete the duplicate base class specifier; we're going to
2461 // overwrite its pointer later.
2462 Context.Deallocate(Bases[idx]);
2463
2464 Invalid = true;
2465 } else {
2466 // Okay, add this new base class.
2467 KnownBase = Bases[idx];
2468 Bases[NumGoodBases++] = Bases[idx];
2469
2470 // Note this base's direct & indirect bases, if there could be ambiguity.
2471 if (Bases.size() > 1)
2472 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2473
2474 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2475 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2476 if (Class->isInterface() &&
2477 (!RD->isInterfaceLike() ||
2478 KnownBase->getAccessSpecifier() != AS_public)) {
2479 // The Microsoft extension __interface does not permit bases that
2480 // are not themselves public interfaces.
2481 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2482 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2483 << RD->getSourceRange();
2484 Invalid = true;
2485 }
2486 if (RD->hasAttr<WeakAttr>())
2487 Class->addAttr(WeakAttr::CreateImplicit(Context));
2488 }
2489 }
2490 }
2491
2492 // Attach the remaining base class specifiers to the derived class.
2493 Class->setBases(Bases.data(), NumGoodBases);
2494
2495 // Check that the only base classes that are duplicate are virtual.
2496 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2497 // Check whether this direct base is inaccessible due to ambiguity.
2498 QualType BaseType = Bases[idx]->getType();
2499
2500 // Skip all dependent types in templates being used as base specifiers.
2501 // Checks below assume that the base specifier is a CXXRecord.
2502 if (BaseType->isDependentType())
2503 continue;
2504
2505 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2506 .getUnqualifiedType();
2507
2508 if (IndirectBaseTypes.count(CanonicalBase)) {
2509 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2510 /*DetectVirtual=*/true);
2511 bool found
2512 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2513 assert(found);
2514 (void)found;
2515
2516 if (Paths.isAmbiguous(CanonicalBase))
2517 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2518 << BaseType << getAmbiguousPathsDisplayString(Paths)
2519 << Bases[idx]->getSourceRange();
2520 else
2521 assert(Bases[idx]->isVirtual());
2522 }
2523
2524 // Delete the base class specifier, since its data has been copied
2525 // into the CXXRecordDecl.
2526 Context.Deallocate(Bases[idx]);
2527 }
2528
2529 return Invalid;
2530}
2531
2532/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2533/// class, after checking whether there are any duplicate base
2534/// classes.
2535void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2536 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2537 if (!ClassDecl || Bases.empty())
2538 return;
2539
2540 AdjustDeclIfTemplate(ClassDecl);
2541 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2542}
2543
2544/// Determine whether the type \p Derived is a C++ class that is
2545/// derived from the type \p Base.
2546bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2547 if (!getLangOpts().CPlusPlus)
2548 return false;
2549
2550 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2551 if (!DerivedRD)
2552 return false;
2553
2554 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2555 if (!BaseRD)
2556 return false;
2557
2558 // If either the base or the derived type is invalid, don't try to
2559 // check whether one is derived from the other.
2560 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2561 return false;
2562
2563 // FIXME: In a modules build, do we need the entire path to be visible for us
2564 // to be able to use the inheritance relationship?
2565 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2566 return false;
2567
2568 return DerivedRD->isDerivedFrom(BaseRD);
2569}
2570
2571/// Determine whether the type \p Derived is a C++ class that is
2572/// derived from the type \p Base.
2573bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2574 CXXBasePaths &Paths) {
2575 if (!getLangOpts().CPlusPlus)
2576 return false;
2577
2578 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2579 if (!DerivedRD)
2580 return false;
2581
2582 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2583 if (!BaseRD)
2584 return false;
2585
2586 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2587 return false;
2588
2589 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2590}
2591
2592static void BuildBasePathArray(const CXXBasePath &Path,
2593 CXXCastPath &BasePathArray) {
2594 // We first go backward and check if we have a virtual base.
2595 // FIXME: It would be better if CXXBasePath had the base specifier for
2596 // the nearest virtual base.
2597 unsigned Start = 0;
2598 for (unsigned I = Path.size(); I != 0; --I) {
2599 if (Path[I - 1].Base->isVirtual()) {
2600 Start = I - 1;
2601 break;
2602 }
2603 }
2604
2605 // Now add all bases.
2606 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2607 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2608}
2609
2610
2611void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2612 CXXCastPath &BasePathArray) {
2613 assert(BasePathArray.empty() && "Base path array must be empty!");
2614 assert(Paths.isRecordingPaths() && "Must record paths!");
2615 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2616}
2617/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2618/// conversion (where Derived and Base are class types) is
2619/// well-formed, meaning that the conversion is unambiguous (and
2620/// that all of the base classes are accessible). Returns true
2621/// and emits a diagnostic if the code is ill-formed, returns false
2622/// otherwise. Loc is the location where this routine should point to
2623/// if there is an error, and Range is the source range to highlight
2624/// if there is an error.
2625///
2626/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2627/// diagnostic for the respective type of error will be suppressed, but the
2628/// check for ill-formed code will still be performed.
2629bool
2630Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2631 unsigned InaccessibleBaseID,
2632 unsigned AmbigiousBaseConvID,
2633 SourceLocation Loc, SourceRange Range,
2634 DeclarationName Name,
2635 CXXCastPath *BasePath,
2636 bool IgnoreAccess) {
2637 // First, determine whether the path from Derived to Base is
2638 // ambiguous. This is slightly more expensive than checking whether
2639 // the Derived to Base conversion exists, because here we need to
2640 // explore multiple paths to determine if there is an ambiguity.
2641 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2642 /*DetectVirtual=*/false);
2643 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2644 if (!DerivationOkay)
2645 return true;
2646
2647 const CXXBasePath *Path = nullptr;
2648 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2649 Path = &Paths.front();
2650
2651 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2652 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2653 // user to access such bases.
2654 if (!Path && getLangOpts().MSVCCompat) {
2655 for (const CXXBasePath &PossiblePath : Paths) {
2656 if (PossiblePath.size() == 1) {
2657 Path = &PossiblePath;
2658 if (AmbigiousBaseConvID)
2659 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2660 << Base << Derived << Range;
2661 break;
2662 }
2663 }
2664 }
2665
2666 if (Path) {
2667 if (!IgnoreAccess) {
2668 // Check that the base class can be accessed.
2669 switch (
2670 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2671 case AR_inaccessible:
2672 return true;
2673 case AR_accessible:
2674 case AR_dependent:
2675 case AR_delayed:
2676 break;
2677 }
2678 }
2679
2680 // Build a base path if necessary.
2681 if (BasePath)
2682 ::BuildBasePathArray(*Path, *BasePath);
2683 return false;
2684 }
2685
2686 if (AmbigiousBaseConvID) {
2687 // We know that the derived-to-base conversion is ambiguous, and
2688 // we're going to produce a diagnostic. Perform the derived-to-base
2689 // search just one more time to compute all of the possible paths so
2690 // that we can print them out. This is more expensive than any of
2691 // the previous derived-to-base checks we've done, but at this point
2692 // performance isn't as much of an issue.
2693 Paths.clear();
2694 Paths.setRecordingPaths(true);
2695 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2696 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2697 (void)StillOkay;
2698
2699 // Build up a textual representation of the ambiguous paths, e.g.,
2700 // D -> B -> A, that will be used to illustrate the ambiguous
2701 // conversions in the diagnostic. We only print one of the paths
2702 // to each base class subobject.
2703 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2704
2705 Diag(Loc, AmbigiousBaseConvID)
2706 << Derived << Base << PathDisplayStr << Range << Name;
2707 }
2708 return true;
2709}
2710
2711bool
2712Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2713 SourceLocation Loc, SourceRange Range,
2714 CXXCastPath *BasePath,
2715 bool IgnoreAccess) {
2716 return CheckDerivedToBaseConversion(
2717 Derived, Base, diag::err_upcast_to_inaccessible_base,
2718 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2719 BasePath, IgnoreAccess);
2720}
2721
2722
2723/// Builds a string representing ambiguous paths from a
2724/// specific derived class to different subobjects of the same base
2725/// class.
2726///
2727/// This function builds a string that can be used in error messages
2728/// to show the different paths that one can take through the
2729/// inheritance hierarchy to go from the derived class to different
2730/// subobjects of a base class. The result looks something like this:
2731/// @code
2732/// struct D -> struct B -> struct A
2733/// struct D -> struct C -> struct A
2734/// @endcode
2735std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2736 std::string PathDisplayStr;
2737 std::set<unsigned> DisplayedPaths;
2738 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2739 Path != Paths.end(); ++Path) {
2740 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2741 // We haven't displayed a path to this particular base
2742 // class subobject yet.
2743 PathDisplayStr += "\n ";
2744 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2745 for (CXXBasePath::const_iterator Element = Path->begin();
2746 Element != Path->end(); ++Element)
2747 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2748 }
2749 }
2750
2751 return PathDisplayStr;
2752}
2753
2754//===----------------------------------------------------------------------===//
2755// C++ class member Handling
2756//===----------------------------------------------------------------------===//
2757
2758/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2759bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2760 SourceLocation ColonLoc,
2761 const ParsedAttributesView &Attrs) {
2762 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2763 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2764 ASLoc, ColonLoc);
2765 CurContext->addHiddenDecl(ASDecl);
2766 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2767}
2768
2769/// CheckOverrideControl - Check C++11 override control semantics.
2770void Sema::CheckOverrideControl(NamedDecl *D) {
2771 if (D->isInvalidDecl())
2772 return;
2773
2774 // We only care about "override" and "final" declarations.
2775 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2776 return;
2777
2778 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2779
2780 // We can't check dependent instance methods.
2781 if (MD && MD->isInstance() &&
2782 (MD->getParent()->hasAnyDependentBases() ||
2783 MD->getType()->isDependentType()))
2784 return;
2785
2786 if (MD && !MD->isVirtual()) {
2787 // If we have a non-virtual method, check if if hides a virtual method.
2788 // (In that case, it's most likely the method has the wrong type.)
2789 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2790 FindHiddenVirtualMethods(MD, OverloadedMethods);
2791
2792 if (!OverloadedMethods.empty()) {
2793 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2794 Diag(OA->getLocation(),
2795 diag::override_keyword_hides_virtual_member_function)
2796 << "override" << (OverloadedMethods.size() > 1);
2797 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2798 Diag(FA->getLocation(),
2799 diag::override_keyword_hides_virtual_member_function)
2800 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2801 << (OverloadedMethods.size() > 1);
2802 }
2803 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2804 MD->setInvalidDecl();
2805 return;
2806 }
2807 // Fall through into the general case diagnostic.
2808 // FIXME: We might want to attempt typo correction here.
2809 }
2810
2811 if (!MD || !MD->isVirtual()) {
2812 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2813 Diag(OA->getLocation(),
2814 diag::override_keyword_only_allowed_on_virtual_member_functions)
2815 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2816 D->dropAttr<OverrideAttr>();
2817 }
2818 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2819 Diag(FA->getLocation(),
2820 diag::override_keyword_only_allowed_on_virtual_member_functions)
2821 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2822 << FixItHint::CreateRemoval(FA->getLocation());
2823 D->dropAttr<FinalAttr>();
2824 }
2825 return;
2826 }
2827
2828 // C++11 [class.virtual]p5:
2829 // If a function is marked with the virt-specifier override and
2830 // does not override a member function of a base class, the program is
2831 // ill-formed.
2832 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2833 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2834 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2835 << MD->getDeclName();
2836}
2837
2838void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2839 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2840 return;
2841 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2842 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2843 return;
2844
2845 SourceLocation Loc = MD->getLocation();
2846 SourceLocation SpellingLoc = Loc;
2847 if (getSourceManager().isMacroArgExpansion(Loc))
2848 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2849 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2850 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2851 return;
2852
2853 if (MD->size_overridden_methods() > 0) {
2854 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2855 ? diag::warn_destructor_marked_not_override_overriding
2856 : diag::warn_function_marked_not_override_overriding;
2857 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2858 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2859 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2860 }
2861}
2862
2863/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2864/// function overrides a virtual member function marked 'final', according to
2865/// C++11 [class.virtual]p4.
2866bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2867 const CXXMethodDecl *Old) {
2868 FinalAttr *FA = Old->getAttr<FinalAttr>();
2869 if (!FA)
2870 return false;
2871
2872 Diag(New->getLocation(), diag::err_final_function_overridden)
2873 << New->getDeclName()
2874 << FA->isSpelledAsSealed();
2875 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2876 return true;
2877}
2878
2879static bool InitializationHasSideEffects(const FieldDecl &FD) {
2880 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2881 // FIXME: Destruction of ObjC lifetime types has side-effects.
2882 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2883 return !RD->isCompleteDefinition() ||
2884 !RD->hasTrivialDefaultConstructor() ||
2885 !RD->hasTrivialDestructor();
2886 return false;
2887}
2888
2889static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2890 ParsedAttributesView::const_iterator Itr =
2891 llvm::find_if(list, [](const ParsedAttr &AL) {
2892 return AL.isDeclspecPropertyAttribute();
2893 });
2894 if (Itr != list.end())
2895 return &*Itr;
2896 return nullptr;
2897}
2898
2899// Check if there is a field shadowing.
2900void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2901 DeclarationName FieldName,
2902 const CXXRecordDecl *RD,
2903 bool DeclIsField) {
2904 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2905 return;
2906
2907 // To record a shadowed field in a base
2908 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2909 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2910 CXXBasePath &Path) {
2911 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2912 // Record an ambiguous path directly
2913 if (Bases.find(Base) != Bases.end())
2914 return true;
2915 for (const auto Field : Base->lookup(FieldName)) {
2916 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2917 Field->getAccess() != AS_private) {
2918 assert(Field->getAccess() != AS_none);
2919 assert(Bases.find(Base) == Bases.end());
2920 Bases[Base] = Field;
2921 return true;
2922 }
2923 }
2924 return false;
2925 };
2926
2927 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2928 /*DetectVirtual=*/true);
2929 if (!RD->lookupInBases(FieldShadowed, Paths))
2930 return;
2931
2932 for (const auto &P : Paths) {
2933 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2934 auto It = Bases.find(Base);
2935 // Skip duplicated bases
2936 if (It == Bases.end())
2937 continue;
2938 auto BaseField = It->second;
2939 assert(BaseField->getAccess() != AS_private);
2940 if (AS_none !=
2941 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2942 Diag(Loc, diag::warn_shadow_field)
2943 << FieldName << RD << Base << DeclIsField;
2944 Diag(BaseField->getLocation(), diag::note_shadow_field);
2945 Bases.erase(It);
2946 }
2947 }
2948}
2949
2950/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2951/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2952/// bitfield width if there is one, 'InitExpr' specifies the initializer if
2953/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2954/// present (but parsing it has been deferred).
2955NamedDecl *
2956Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2957 MultiTemplateParamsArg TemplateParameterLists,
2958 Expr *BW, const VirtSpecifiers &VS,
2959 InClassInitStyle InitStyle) {
2960 const DeclSpec &DS = D.getDeclSpec();
2961 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2962 DeclarationName Name = NameInfo.getName();
2963 SourceLocation Loc = NameInfo.getLoc();
2964
2965 // For anonymous bitfields, the location should point to the type.
2966 if (Loc.isInvalid())
2967 Loc = D.getBeginLoc();
2968
2969 Expr *BitWidth = static_cast<Expr*>(BW);
2970
2971 assert(isa<CXXRecordDecl>(CurContext));
2972 assert(!DS.isFriendSpecified());
2973
2974 bool isFunc = D.isDeclarationOfFunction();
2975 const ParsedAttr *MSPropertyAttr =
2976 getMSPropertyAttr(D.getDeclSpec().getAttributes());
2977
2978 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2979 // The Microsoft extension __interface only permits public member functions
2980 // and prohibits constructors, destructors, operators, non-public member
2981 // functions, static methods and data members.
2982 unsigned InvalidDecl;
2983 bool ShowDeclName = true;
2984 if (!isFunc &&
2985 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2986 InvalidDecl = 0;
2987 else if (!isFunc)
2988 InvalidDecl = 1;
2989 else if (AS != AS_public)
2990 InvalidDecl = 2;
2991 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2992 InvalidDecl = 3;
2993 else switch (Name.getNameKind()) {
2994 case DeclarationName::CXXConstructorName:
2995 InvalidDecl = 4;
2996 ShowDeclName = false;
2997 break;
2998
2999 case DeclarationName::CXXDestructorName:
3000 InvalidDecl = 5;
3001 ShowDeclName = false;
3002 break;
3003
3004 case DeclarationName::CXXOperatorName:
3005 case DeclarationName::CXXConversionFunctionName:
3006 InvalidDecl = 6;
3007 break;
3008
3009 default:
3010 InvalidDecl = 0;
3011 break;
3012 }
3013
3014 if (InvalidDecl) {
3015 if (ShowDeclName)
3016 Diag(Loc, diag::err_invalid_member_in_interface)
3017 << (InvalidDecl-1) << Name;
3018 else
3019 Diag(Loc, diag::err_invalid_member_in_interface)
3020 << (InvalidDecl-1) << "";
3021 return nullptr;
3022 }
3023 }
3024
3025 // C++ 9.2p6: A member shall not be declared to have automatic storage
3026 // duration (auto, register) or with the extern storage-class-specifier.
3027 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3028 // data members and cannot be applied to names declared const or static,
3029 // and cannot be applied to reference members.
3030 switch (DS.getStorageClassSpec()) {
3031 case DeclSpec::SCS_unspecified:
3032 case DeclSpec::SCS_typedef:
3033 case DeclSpec::SCS_static:
3034 break;
3035 case DeclSpec::SCS_mutable:
3036 if (isFunc) {
3037 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3038
3039 // FIXME: It would be nicer if the keyword was ignored only for this
3040 // declarator. Otherwise we could get follow-up errors.
3041 D.getMutableDeclSpec().ClearStorageClassSpecs();
3042 }
3043 break;
3044 default:
3045 Diag(DS.getStorageClassSpecLoc(),
3046 diag::err_storageclass_invalid_for_member);
3047 D.getMutableDeclSpec().ClearStorageClassSpecs();
3048 break;
3049 }
3050
3051 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3052 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3053 !isFunc);
3054
3055 if (DS.isConstexprSpecified() && isInstField) {
3056 SemaDiagnosticBuilder B =
3057 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3058 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3059 if (InitStyle == ICIS_NoInit) {
3060 B << 0 << 0;
3061 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3062 B << FixItHint::CreateRemoval(ConstexprLoc);
3063 else {
3064 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3065 D.getMutableDeclSpec().ClearConstexprSpec();
3066 const char *PrevSpec;
3067 unsigned DiagID;
3068 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3069 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3070 (void)Failed;
3071 assert(!Failed && "Making a constexpr member const shouldn't fail");
3072 }
3073 } else {
3074 B << 1;
3075 const char *PrevSpec;
3076 unsigned DiagID;
3077 if (D.getMutableDeclSpec().SetStorageClassSpec(
3078 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3079 Context.getPrintingPolicy())) {
3080 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3081 "This is the only DeclSpec that should fail to be applied");
3082 B << 1;
3083 } else {
3084 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3085 isInstField = false;
3086 }
3087 }
3088 }
3089
3090 NamedDecl *Member;
3091 if (isInstField) {
3092 CXXScopeSpec &SS = D.getCXXScopeSpec();
3093
3094 // Data members must have identifiers for names.
3095 if (!Name.isIdentifier()) {
3096 Diag(Loc, diag::err_bad_variable_name)
3097 << Name;
3098 return nullptr;
3099 }
3100
3101 IdentifierInfo *II = Name.getAsIdentifierInfo();
3102
3103 // Member field could not be with "template" keyword.
3104 // So TemplateParameterLists should be empty in this case.
3105 if (TemplateParameterLists.size()) {
3106 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3107 if (TemplateParams->size()) {
3108 // There is no such thing as a member field template.
3109 Diag(D.getIdentifierLoc(), diag::err_template_member)
3110 << II
3111 << SourceRange(TemplateParams->getTemplateLoc(),
3112 TemplateParams->getRAngleLoc());
3113 } else {
3114 // There is an extraneous 'template<>' for this member.
3115 Diag(TemplateParams->getTemplateLoc(),
3116 diag::err_template_member_noparams)
3117 << II
3118 << SourceRange(TemplateParams->getTemplateLoc(),
3119 TemplateParams->getRAngleLoc());
3120 }
3121 return nullptr;
3122 }
3123
3124 if (SS.isSet() && !SS.isInvalid()) {
3125 // The user provided a superfluous scope specifier inside a class
3126 // definition:
3127 //
3128 // class X {
3129 // int X::member;
3130 // };
3131 if (DeclContext *DC = computeDeclContext(SS, false))
3132 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3133 D.getName().getKind() ==
3134 UnqualifiedIdKind::IK_TemplateId);
3135 else
3136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3137 << Name << SS.getRange();
3138
3139 SS.clear();
3140 }
3141
3142 if (MSPropertyAttr) {
3143 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3144 BitWidth, InitStyle, AS, *MSPropertyAttr);
3145 if (!Member)
3146 return nullptr;
3147 isInstField = false;
3148 } else {
3149 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3150 BitWidth, InitStyle, AS);
3151 if (!Member)
3152 return nullptr;
3153 }
3154
3155 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3156 } else {
3157 Member = HandleDeclarator(S, D, TemplateParameterLists);
3158 if (!Member)
3159 return nullptr;
3160
3161 // Non-instance-fields can't have a bitfield.
3162 if (BitWidth) {
3163 if (Member->isInvalidDecl()) {
3164 // don't emit another diagnostic.
3165 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3166 // C++ 9.6p3: A bit-field shall not be a static member.
3167 // "static member 'A' cannot be a bit-field"
3168 Diag(Loc, diag::err_static_not_bitfield)
3169 << Name << BitWidth->getSourceRange();
3170 } else if (isa<TypedefDecl>(Member)) {
3171 // "typedef member 'x' cannot be a bit-field"
3172 Diag(Loc, diag::err_typedef_not_bitfield)
3173 << Name << BitWidth->getSourceRange();
3174 } else {
3175 // A function typedef ("typedef int f(); f a;").
3176 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3177 Diag(Loc, diag::err_not_integral_type_bitfield)
3178 << Name << cast<ValueDecl>(Member)->getType()
3179 << BitWidth->getSourceRange();
3180 }
3181
3182 BitWidth = nullptr;
3183 Member->setInvalidDecl();
3184 }
3185
3186 NamedDecl *NonTemplateMember = Member;
3187 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3188 NonTemplateMember = FunTmpl->getTemplatedDecl();
3189 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3190 NonTemplateMember = VarTmpl->getTemplatedDecl();
3191
3192 Member->setAccess(AS);
3193
3194 // If we have declared a member function template or static data member
3195 // template, set the access of the templated declaration as well.
3196 if (NonTemplateMember != Member)
3197 NonTemplateMember->setAccess(AS);
3198
3199 // C++ [temp.deduct.guide]p3:
3200 // A deduction guide [...] for a member class template [shall be
3201 // declared] with the same access [as the template].
3202 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3203 auto *TD = DG->getDeducedTemplate();
3204 // Access specifiers are only meaningful if both the template and the
3205 // deduction guide are from the same scope.
3206 if (AS != TD->getAccess() &&
3207 TD->getDeclContext()->getRedeclContext()->Equals(
3208 DG->getDeclContext()->getRedeclContext())) {
3209 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3210 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3211 << TD->getAccess();
3212 const AccessSpecDecl *LastAccessSpec = nullptr;
3213 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3214 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3215 LastAccessSpec = AccessSpec;
3216 }
3217 assert(LastAccessSpec && "differing access with no access specifier");
3218 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3219 << AS;
3220 }
3221 }
3222 }
3223
3224 if (VS.isOverrideSpecified())
3225 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3226 if (VS.isFinalSpecified())
3227 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3228 VS.isFinalSpelledSealed()));
3229
3230 if (VS.getLastLocation().isValid()) {
3231 // Update the end location of a method that has a virt-specifiers.
3232 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3233 MD->setRangeEnd(VS.getLastLocation());
3234 }
3235
3236 CheckOverrideControl(Member);
3237
3238 assert((Name || isInstField) && "No identifier for non-field ?");
3239
3240 if (isInstField) {
3241 FieldDecl *FD = cast<FieldDecl>(Member);
3242 FieldCollector->Add(FD);
3243
3244 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3245 // Remember all explicit private FieldDecls that have a name, no side
3246 // effects and are not part of a dependent type declaration.
3247 if (!FD->isImplicit() && FD->getDeclName() &&
3248 FD->getAccess() == AS_private &&
3249 !FD->hasAttr<UnusedAttr>() &&
3250 !FD->getParent()->isDependentContext() &&
3251 !InitializationHasSideEffects(*FD))
3252 UnusedPrivateFields.insert(FD);
3253 }
3254 }
3255
3256 return Member;
3257}
3258
3259namespace {
3260 class UninitializedFieldVisitor
3261 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3262 Sema &S;
3263 // List of Decls to generate a warning on. Also remove Decls that become
3264 // initialized.
3265 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3266 // List of base classes of the record. Classes are removed after their
3267 // initializers.
3268 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3269 // Vector of decls to be removed from the Decl set prior to visiting the
3270 // nodes. These Decls may have been initialized in the prior initializer.
3271 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3272 // If non-null, add a note to the warning pointing back to the constructor.
3273 const CXXConstructorDecl *Constructor;
3274 // Variables to hold state when processing an initializer list. When
3275 // InitList is true, special case initialization of FieldDecls matching
3276 // InitListFieldDecl.
3277 bool InitList;
3278 FieldDecl *InitListFieldDecl;
3279 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3280
3281 public:
3282 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3283 UninitializedFieldVisitor(Sema &S,
3284 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3285 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3286 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3287 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3288
3289 // Returns true if the use of ME is not an uninitialized use.
3290 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3291 bool CheckReferenceOnly) {
3292 llvm::SmallVector<FieldDecl*, 4> Fields;
3293 bool ReferenceField = false;
3294 while (ME) {
3295 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3296 if (!FD)
3297 return false;
3298 Fields.push_back(FD);
3299 if (FD->getType()->isReferenceType())
3300 ReferenceField = true;
3301 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3302 }
3303
3304 // Binding a reference to an uninitialized field is not an
3305 // uninitialized use.
3306 if (CheckReferenceOnly && !ReferenceField)
3307 return true;
3308
3309 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3310 // Discard the first field since it is the field decl that is being
3311 // initialized.
3312 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3313 UsedFieldIndex.push_back((*I)->getFieldIndex());
3314 }
3315
3316 for (auto UsedIter = UsedFieldIndex.begin(),
3317 UsedEnd = UsedFieldIndex.end(),
3318 OrigIter = InitFieldIndex.begin(),
3319 OrigEnd = InitFieldIndex.end();
3320 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3321 if (*UsedIter < *OrigIter)
3322 return true;
3323 if (*UsedIter > *OrigIter)
3324 break;
3325 }
3326
3327 return false;
3328 }
3329
3330 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3331 bool AddressOf) {
3332 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3333 return;
3334
3335 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3336 // or union.
3337 MemberExpr *FieldME = ME;
3338
3339 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3340
3341 Expr *Base = ME;
3342 while (MemberExpr *SubME =
3343 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3344
3345 if (isa<VarDecl>(SubME->getMemberDecl()))
3346 return;
3347
3348 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3349 if (!FD->isAnonymousStructOrUnion())
3350 FieldME = SubME;
3351
3352 if (!FieldME->getType().isPODType(S.Context))
3353 AllPODFields = false;
3354
3355 Base = SubME->getBase();
3356 }
3357
3358 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3359 return;
3360
3361 if (AddressOf && AllPODFields)
3362 return;
3363
3364 ValueDecl* FoundVD = FieldME->getMemberDecl();
3365
3366 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3367 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3368 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3369 }
3370
3371 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3372 QualType T = BaseCast->getType();
3373 if (T->isPointerType() &&
3374 BaseClasses.count(T->getPointeeType())) {
3375 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3376 << T->getPointeeType() << FoundVD;
3377 }
3378 }
3379 }
3380
3381 if (!Decls.count(FoundVD))
3382 return;
3383
3384 const bool IsReference = FoundVD->getType()->isReferenceType();
3385
3386 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3387 // Special checking for initializer lists.
3388 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3389 return;
3390 }
3391 } else {
3392 // Prevent double warnings on use of unbounded references.
3393 if (CheckReferenceOnly && !IsReference)
3394 return;
3395 }
3396
3397 unsigned diag = IsReference
3398 ? diag::warn_reference_field_is_uninit
3399 : diag::warn_field_is_uninit;
3400 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3401 if (Constructor)
3402 S.Diag(Constructor->getLocation(),
3403 diag::note_uninit_in_this_constructor)
3404 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3405
3406 }
3407
3408 void HandleValue(Expr *E, bool AddressOf) {
3409 E = E->IgnoreParens();
3410
3411 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3412 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3413 AddressOf /*AddressOf*/);
3414 return;
3415 }
3416
3417 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3418 Visit(CO->getCond());
3419 HandleValue(CO->getTrueExpr(), AddressOf);
3420 HandleValue(CO->getFalseExpr(), AddressOf);
3421 return;
3422 }
3423
3424 if (BinaryConditionalOperator *BCO =
3425 dyn_cast<BinaryConditionalOperator>(E)) {
3426 Visit(BCO->getCond());
3427 HandleValue(BCO->getFalseExpr(), AddressOf);
3428 return;
3429 }
3430
3431 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3432 HandleValue(OVE->getSourceExpr(), AddressOf);
3433 return;
3434 }
3435
3436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3437 switch (BO->getOpcode()) {
3438 default:
3439 break;
3440 case(BO_PtrMemD):
3441 case(BO_PtrMemI):
3442 HandleValue(BO->getLHS(), AddressOf);
3443 Visit(BO->getRHS());
3444 return;
3445 case(BO_Comma):
3446 Visit(BO->getLHS());
3447 HandleValue(BO->getRHS(), AddressOf);
3448 return;
3449 }
3450 }
3451
3452 Visit(E);
3453 }
3454
3455 void CheckInitListExpr(InitListExpr *ILE) {
3456 InitFieldIndex.push_back(0);
3457 for (auto Child : ILE->children()) {
3458 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3459 CheckInitListExpr(SubList);
3460 } else {
3461 Visit(Child);
3462 }
3463 ++InitFieldIndex.back();
3464 }
3465 InitFieldIndex.pop_back();
3466 }
3467
3468 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3469 FieldDecl *Field, const Type *BaseClass) {
3470 // Remove Decls that may have been initialized in the previous
3471 // initializer.
3472 for (ValueDecl* VD : DeclsToRemove)
3473 Decls.erase(VD);
3474 DeclsToRemove.clear();
3475
3476 Constructor = FieldConstructor;
3477 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3478
3479 if (ILE && Field) {
3480 InitList = true;
3481 InitListFieldDecl = Field;
3482 InitFieldIndex.clear();
3483 CheckInitListExpr(ILE);
3484 } else {
3485 InitList = false;
3486 Visit(E);
3487 }
3488
3489 if (Field)
3490 Decls.erase(Field);
3491 if (BaseClass)
3492 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3493 }
3494
3495 void VisitMemberExpr(MemberExpr *ME) {
3496 // All uses of unbounded reference fields will warn.
3497 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3498 }
3499
3500 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3501 if (E->getCastKind() == CK_LValueToRValue) {
3502 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3503 return;
3504 }
3505
3506 Inherited::VisitImplicitCastExpr(E);
3507 }
3508
3509 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3510 if (E->getConstructor()->isCopyConstructor()) {
3511 Expr *ArgExpr = E->getArg(0);
3512 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3513 if (ILE->getNumInits() == 1)
3514 ArgExpr = ILE->getInit(0);
3515 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3516 if (ICE->getCastKind() == CK_NoOp)
3517 ArgExpr = ICE->getSubExpr();
3518 HandleValue(ArgExpr, false /*AddressOf*/);
3519 return;
3520 }
3521 Inherited::VisitCXXConstructExpr(E);
3522 }
3523
3524 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3525 Expr *Callee = E->getCallee();
3526 if (isa<MemberExpr>(Callee)) {
3527 HandleValue(Callee, false /*AddressOf*/);
3528 for (auto Arg : E->arguments())
3529 Visit(Arg);
3530 return;
3531 }
3532
3533 Inherited::VisitCXXMemberCallExpr(E);
3534 }
3535
3536 void VisitCallExpr(CallExpr *E) {
3537 // Treat std::move as a use.
3538 if (E->isCallToStdMove()) {
3539 HandleValue(E->getArg(0), /*AddressOf=*/false);
3540 return;
3541 }
3542
3543 Inherited::VisitCallExpr(E);
3544 }
3545
3546 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3547 Expr *Callee = E->getCallee();
3548
3549 if (isa<UnresolvedLookupExpr>(Callee))
3550 return Inherited::VisitCXXOperatorCallExpr(E);
3551
3552 Visit(Callee);
3553 for (auto Arg : E->arguments())
3554 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3555 }
3556
3557 void VisitBinaryOperator(BinaryOperator *E) {
3558 // If a field assignment is detected, remove the field from the
3559 // uninitiailized field set.
3560 if (E->getOpcode() == BO_Assign)
3561 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3562 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3563 if (!FD->getType()->isReferenceType())
3564 DeclsToRemove.push_back(FD);
3565
3566 if (E->isCompoundAssignmentOp()) {
3567 HandleValue(E->getLHS(), false /*AddressOf*/);
3568 Visit(E->getRHS());
3569 return;
3570 }
3571
3572 Inherited::VisitBinaryOperator(E);
3573 }
3574
3575 void VisitUnaryOperator(UnaryOperator *E) {
3576 if (E->isIncrementDecrementOp()) {
3577 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3578 return;
3579 }
3580 if (E->getOpcode() == UO_AddrOf) {
3581 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3582 HandleValue(ME->getBase(), true /*AddressOf*/);
3583 return;
3584 }
3585 }
3586
3587 Inherited::VisitUnaryOperator(E);
3588 }
3589 };
3590
3591 // Diagnose value-uses of fields to initialize themselves, e.g.
3592 // foo(foo)
3593 // where foo is not also a parameter to the constructor.
3594 // Also diagnose across field uninitialized use such as
3595 // x(y), y(x)
3596 // TODO: implement -Wuninitialized and fold this into that framework.
3597 static void DiagnoseUninitializedFields(
3598 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3599
3600 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3601 Constructor->getLocation())) {
3602 return;
3603 }
3604
3605 if (Constructor->isInvalidDecl())
3606 return;
3607
3608 const CXXRecordDecl *RD = Constructor->getParent();
3609
3610 if (RD->getDescribedClassTemplate())
3611 return;
3612
3613 // Holds fields that are uninitialized.
3614 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3615
3616 // At the beginning, all fields are uninitialized.
3617 for (auto *I : RD->decls()) {
3618 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3619 UninitializedFields.insert(FD);
3620 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3621 UninitializedFields.insert(IFD->getAnonField());
3622 }
3623 }
3624
3625 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3626 for (auto I : RD->bases())
3627 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3628
3629 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3630 return;
3631
3632 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3633 UninitializedFields,
3634 UninitializedBaseClasses);
3635
3636 for (const auto *FieldInit : Constructor->inits()) {
3637 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3638 break;
3639
3640 Expr *InitExpr = FieldInit->getInit();
3641 if (!InitExpr)
3642 continue;
3643
3644 if (CXXDefaultInitExpr *Default =
3645 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3646 InitExpr = Default->getExpr();
3647 if (!InitExpr)
3648 continue;
3649 // In class initializers will point to the constructor.
3650 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3651 FieldInit->getAnyMember(),
3652 FieldInit->getBaseClass());
3653 } else {
3654 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3655 FieldInit->getAnyMember(),
3656 FieldInit->getBaseClass());
3657 }
3658 }
3659 }
3660} // namespace
3661
3662/// Enter a new C++ default initializer scope. After calling this, the
3663/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3664/// parsing or instantiating the initializer failed.
3665void Sema::ActOnStartCXXInClassMemberInitializer() {
3666 // Create a synthetic function scope to represent the call to the constructor
3667 // that notionally surrounds a use of this initializer.
3668 PushFunctionScope();
3669}
3670
3671/// This is invoked after parsing an in-class initializer for a
3672/// non-static C++ class member, and after instantiating an in-class initializer
3673/// in a class template. Such actions are deferred until the class is complete.
3674void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3675 SourceLocation InitLoc,
3676 Expr *InitExpr) {
3677 // Pop the notional constructor scope we created earlier.
3678 PopFunctionScopeInfo(nullptr, D);
3679
3680 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3681 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3682 "must set init style when field is created");
3683
3684 if (!InitExpr) {
3685 D->setInvalidDecl();
3686 if (FD)
3687 FD->removeInClassInitializer();
3688 return;
3689 }
3690
3691 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3692 FD->setInvalidDecl();
3693 FD->removeInClassInitializer();
3694 return;
3695 }
3696
3697 ExprResult Init = InitExpr;
3698 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3699 InitializedEntity Entity =
3700 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3701 InitializationKind Kind =
3702 FD->getInClassInitStyle() == ICIS_ListInit
3703 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3704 InitExpr->getBeginLoc(),
3705 InitExpr->getEndLoc())
3706 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3707 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3708 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3709 if (Init.isInvalid()) {
3710 FD->setInvalidDecl();
3711 return;
3712 }
3713 }
3714
3715 // C++11 [class.base.init]p7:
3716 // The initialization of each base and member constitutes a
3717 // full-expression.
3718 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3719 if (Init.isInvalid()) {
3720 FD->setInvalidDecl();
3721 return;
3722 }
3723
3724 InitExpr = Init.get();
3725
3726 FD->setInClassInitializer(InitExpr);
3727}
3728
3729/// Find the direct and/or virtual base specifiers that
3730/// correspond to the given base type, for use in base initialization
3731/// within a constructor.
3732static bool FindBaseInitializer(Sema &SemaRef,
3733 CXXRecordDecl *ClassDecl,
3734 QualType BaseType,
3735 const CXXBaseSpecifier *&DirectBaseSpec,
3736 const CXXBaseSpecifier *&VirtualBaseSpec) {
3737 // First, check for a direct base class.
3738 DirectBaseSpec = nullptr;
3739 for (const auto &Base : ClassDecl->bases()) {
3740 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3741 // We found a direct base of this type. That's what we're
3742 // initializing.
3743 DirectBaseSpec = &Base;
3744 break;
3745 }
3746 }
3747
3748 // Check for a virtual base class.
3749 // FIXME: We might be able to short-circuit this if we know in advance that
3750 // there are no virtual bases.
3751 VirtualBaseSpec = nullptr;
3752 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3753 // We haven't found a base yet; search the class hierarchy for a
3754 // virtual base class.
3755 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3756 /*DetectVirtual=*/false);
3757 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3758 SemaRef.Context.getTypeDeclType(ClassDecl),
3759 BaseType, Paths)) {
3760 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3761 Path != Paths.end(); ++Path) {
3762 if (Path->back().Base->isVirtual()) {
3763 VirtualBaseSpec = Path->back().Base;
3764 break;
3765 }
3766 }
3767 }
3768 }
3769
3770 return DirectBaseSpec || VirtualBaseSpec;
3771}
3772
3773/// Handle a C++ member initializer using braced-init-list syntax.
3774MemInitResult
3775Sema::ActOnMemInitializer(Decl *ConstructorD,
3776 Scope *S,
3777 CXXScopeSpec &SS,
3778 IdentifierInfo *MemberOrBase,
3779 ParsedType TemplateTypeTy,
3780 const DeclSpec &DS,
3781 SourceLocation IdLoc,
3782 Expr *InitList,
3783 SourceLocation EllipsisLoc) {
3784 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3785 DS, IdLoc, InitList,
3786 EllipsisLoc);
3787}
3788
3789/// Handle a C++ member initializer using parentheses syntax.
3790MemInitResult
3791Sema::ActOnMemInitializer(Decl *ConstructorD,
3792 Scope *S,
3793 CXXScopeSpec &SS,
3794 IdentifierInfo *MemberOrBase,
3795 ParsedType TemplateTypeTy,
3796 const DeclSpec &DS,
3797 SourceLocation IdLoc,
3798 SourceLocation LParenLoc,
3799 ArrayRef<Expr *> Args,
3800 SourceLocation RParenLoc,
3801 SourceLocation EllipsisLoc) {
3802 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3803 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3804 DS, IdLoc, List, EllipsisLoc);
3805}
3806
3807namespace {
3808
3809// Callback to only accept typo corrections that can be a valid C++ member
3810// intializer: either a non-static field member or a base class.
3811class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3812public:
3813 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3814 : ClassDecl(ClassDecl) {}
3815
3816 bool ValidateCandidate(const TypoCorrection &candidate) override {
3817 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3818 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3819 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3820 return isa<TypeDecl>(ND);
3821 }
3822 return false;
3823 }
3824
3825 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3826 return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3827 }
3828
3829private:
3830 CXXRecordDecl *ClassDecl;
3831};
3832
3833}
3834
3835ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3836 CXXScopeSpec &SS,
3837 ParsedType TemplateTypeTy,
3838 IdentifierInfo *MemberOrBase) {
3839 if (SS.getScopeRep() || TemplateTypeTy)
3840 return nullptr;
3841 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3842 if (Result.empty())
3843 return nullptr;
3844 ValueDecl *Member;
3845 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3846 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3847 return Member;
3848 return nullptr;
3849}
3850
3851/// Handle a C++ member initializer.
3852MemInitResult
3853Sema::BuildMemInitializer(Decl *ConstructorD,
3854 Scope *S,
3855 CXXScopeSpec &SS,
3856 IdentifierInfo *MemberOrBase,
3857 ParsedType TemplateTypeTy,
3858 const DeclSpec &DS,
3859 SourceLocation IdLoc,
3860 Expr *Init,
3861 SourceLocation EllipsisLoc) {
3862 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3863 if (!Res.isUsable())
3864 return true;
3865 Init = Res.get();
3866
3867 if (!ConstructorD)
3868 return true;
3869
3870 AdjustDeclIfTemplate(ConstructorD);
3871
3872 CXXConstructorDecl *Constructor
3873 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3874 if (!Constructor) {
3875 // The user wrote a constructor initializer on a function that is
3876 // not a C++ constructor. Ignore the error for now, because we may
3877 // have more member initializers coming; we'll diagnose it just
3878 // once in ActOnMemInitializers.
3879 return true;
3880 }
3881
3882 CXXRecordDecl *ClassDecl = Constructor->getParent();
3883
3884 // C++ [class.base.init]p2:
3885 // Names in a mem-initializer-id are looked up in the scope of the
3886 // constructor's class and, if not found in that scope, are looked
3887 // up in the scope containing the constructor's definition.
3888 // [Note: if the constructor's class contains a member with the
3889 // same name as a direct or virtual base class of the class, a
3890 // mem-initializer-id naming the member or base class and composed
3891 // of a single identifier refers to the class member. A
3892 // mem-initializer-id for the hidden base class may be specified
3893 // using a qualified name. ]
3894
3895 // Look for a member, first.
3896 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3897 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3898 if (EllipsisLoc.isValid())
3899 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3900 << MemberOrBase
3901 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3902
3903 return BuildMemberInitializer(Member, Init, IdLoc);
3904 }
3905 // It didn't name a member, so see if it names a class.
3906 QualType BaseType;
3907 TypeSourceInfo *TInfo = nullptr;
3908
3909 if (TemplateTypeTy) {
3910 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3911 if (BaseType.isNull())
3912 return true;
3913 } else if (DS.getTypeSpecType() == TST_decltype) {
3914 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3915 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3916 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3917 return true;
3918 } else {
3919 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3920 LookupParsedName(R, S, &SS);
3921
3922 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3923 if (!TyD) {
3924 if (R.isAmbiguous()) return true;
3925
3926 // We don't want access-control diagnostics here.
3927 R.suppressDiagnostics();
3928
3929 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3930 bool NotUnknownSpecialization = false;
3931 DeclContext *DC = computeDeclContext(SS, false);
3932 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3933 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3934
3935 if (!NotUnknownSpecialization) {
3936 // When the scope specifier can refer to a member of an unknown
3937 // specialization, we take it as a type name.
3938 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3939 SS.getWithLocInContext(Context),
3940 *MemberOrBase, IdLoc);
3941 if (BaseType.isNull())
3942 return true;
3943
3944 TInfo = Context.CreateTypeSourceInfo(BaseType);
3945 DependentNameTypeLoc TL =
3946 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3947 if (!TL.isNull()) {
3948 TL.setNameLoc(IdLoc);
3949 TL.setElaboratedKeywordLoc(SourceLocation());
3950 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3951 }
3952
3953 R.clear();
3954 R.setLookupName(MemberOrBase);
3955 }
3956 }
3957
3958 // If no results were found, try to correct typos.
3959 TypoCorrection Corr;
3960 MemInitializerValidatorCCC CCC(ClassDecl);
3961 if (R.empty() && BaseType.isNull() &&
3962 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3963 CCC, CTK_ErrorRecovery, ClassDecl))) {
3964 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3965 // We have found a non-static data member with a similar
3966 // name to what was typed; complain and initialize that
3967 // member.
3968 diagnoseTypo(Corr,
3969 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3970 << MemberOrBase << true);
3971 return BuildMemberInitializer(Member, Init, IdLoc);
3972 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3973 const CXXBaseSpecifier *DirectBaseSpec;
3974 const CXXBaseSpecifier *VirtualBaseSpec;
3975 if (FindBaseInitializer(*this, ClassDecl,
3976 Context.getTypeDeclType(Type),
3977 DirectBaseSpec, VirtualBaseSpec)) {
3978 // We have found a direct or virtual base class with a
3979 // similar name to what was typed; complain and initialize
3980 // that base class.
3981 diagnoseTypo(Corr,
3982 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3983 << MemberOrBase << false,
3984 PDiag() /*Suppress note, we provide our own.*/);
3985
3986 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3987 : VirtualBaseSpec;
3988 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3989 << BaseSpec->getType() << BaseSpec->getSourceRange();
3990
3991 TyD = Type;
3992 }
3993 }
3994 }
3995
3996 if (!TyD && BaseType.isNull()) {
3997 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3998 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3999 return true;
4000 }
4001 }
4002
4003 if (BaseType.isNull()) {
4004 BaseType = Context.getTypeDeclType(TyD);
4005 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4006 if (SS.isSet()) {
4007 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4008 BaseType);
4009 TInfo = Context.CreateTypeSourceInfo(BaseType);
4010 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4011 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4012 TL.setElaboratedKeywordLoc(SourceLocation());
4013 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4014 }
4015 }
4016 }
4017
4018 if (!TInfo)
4019 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4020
4021 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4022}
4023
4024MemInitResult
4025Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4026 SourceLocation IdLoc) {
4027 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4028 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4029 assert((DirectMember || IndirectMember) &&
4030 "Member must be a FieldDecl or IndirectFieldDecl");
4031
4032 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4033 return true;
4034
4035 if (Member->isInvalidDecl())
4036 return true;
4037
4038 MultiExprArg Args;
4039 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4040 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4041 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4042 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4043 } else {
4044 // Template instantiation doesn't reconstruct ParenListExprs for us.
4045 Args = Init;
4046 }
4047
4048 SourceRange InitRange = Init->getSourceRange();
4049
4050 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4051 // Can't check initialization for a member of dependent type or when
4052 // any of the arguments are type-dependent expressions.
4053 DiscardCleanupsInEvaluationContext();
4054 } else {
4055 bool InitList = false;
4056 if (isa<InitListExpr>(Init)) {
4057 InitList = true;
4058 Args = Init;
4059 }
4060
4061 // Initialize the member.
4062 InitializedEntity MemberEntity =
4063 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4064 : InitializedEntity::InitializeMember(IndirectMember,
4065 nullptr);
4066 InitializationKind Kind =
4067 InitList ? InitializationKind::CreateDirectList(
4068 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4069 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4070 InitRange.getEnd());
4071
4072 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4073 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4074 nullptr);
4075 if (MemberInit.isInvalid())
4076 return true;
4077
4078 // C++11 [class.base.init]p7:
4079 // The initialization of each base and member constitutes a
4080 // full-expression.
4081 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4082 /*DiscardedValue*/ false);
4083 if (MemberInit.isInvalid())
4084 return true;
4085
4086 Init = MemberInit.get();
4087 }
4088
4089 if (DirectMember) {
4090 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4091 InitRange.getBegin(), Init,
4092 InitRange.getEnd());
4093 } else {
4094 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4095 InitRange.getBegin(), Init,
4096 InitRange.getEnd());
4097 }
4098}
4099
4100MemInitResult
4101Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4102 CXXRecordDecl *ClassDecl) {
4103 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4104 if (!LangOpts.CPlusPlus11)
4105 return Diag(NameLoc, diag::err_delegating_ctor)
4106 << TInfo->getTypeLoc().getLocalSourceRange();
4107 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4108
4109 bool InitList = true;
4110 MultiExprArg Args = Init;
4111 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4112 InitList = false;
4113 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4114 }
4115
4116 SourceRange InitRange = Init->getSourceRange();
4117 // Initialize the object.
4118 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4119 QualType(ClassDecl->getTypeForDecl(), 0));
4120 InitializationKind Kind =
4121 InitList ? InitializationKind::CreateDirectList(
4122 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4123 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4124 InitRange.getEnd());
4125 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4126 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4127 Args, nullptr);
4128 if (DelegationInit.isInvalid())
4129 return true;
4130
4131 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4132 "Delegating constructor with no target?");
4133
4134 // C++11 [class.base.init]p7:
4135 // The initialization of each base and member constitutes a
4136 // full-expression.
4137 DelegationInit = ActOnFinishFullExpr(
4138 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4139 if (DelegationInit.isInvalid())
4140 return true;
4141
4142 // If we are in a dependent context, template instantiation will
4143 // perform this type-checking again. Just save the arguments that we
4144 // received in a ParenListExpr.
4145 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4146 // of the information that we have about the base
4147 // initializer. However, deconstructing the ASTs is a dicey process,
4148 // and this approach is far more likely to get the corner cases right.
4149 if (CurContext->isDependentContext())
4150 DelegationInit = Init;
4151
4152 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4153 DelegationInit.getAs<Expr>(),
4154 InitRange.getEnd());
4155}
4156
4157MemInitResult
4158Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4159 Expr *Init, CXXRecordDecl *ClassDecl,
4160 SourceLocation EllipsisLoc) {
4161 SourceLocation BaseLoc
4162 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4163
4164 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4165 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4166 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4167
4168 // C++ [class.base.init]p2:
4169 // [...] Unless the mem-initializer-id names a nonstatic data
4170 // member of the constructor's class or a direct or virtual base
4171 // of that class, the mem-initializer is ill-formed. A
4172 // mem-initializer-list can initialize a base class using any
4173 // name that denotes that base class type.
4174 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4175
4176 SourceRange InitRange = Init->getSourceRange();
4177 if (EllipsisLoc.isValid()) {
4178 // This is a pack expansion.
4179 if (!BaseType->containsUnexpandedParameterPack()) {
4180 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4181 << SourceRange(BaseLoc, InitRange.getEnd());
4182
4183 EllipsisLoc = SourceLocation();
4184 }
4185 } else {
4186 // Check for any unexpanded parameter packs.
4187 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4188 return true;
4189
4190 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4191 return true;
4192 }
4193
4194 // Check for direct and virtual base classes.
4195 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4196 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4197 if (!Dependent) {
4198 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4199 BaseType))
4200 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4201
4202 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4203 VirtualBaseSpec);
4204
4205 // C++ [base.class.init]p2:
4206 // Unless the mem-initializer-id names a nonstatic data member of the
4207 // constructor's class or a direct or virtual base of that class, the
4208 // mem-initializer is ill-formed.
4209 if (!DirectBaseSpec && !VirtualBaseSpec) {
4210 // If the class has any dependent bases, then it's possible that
4211 // one of those types will resolve to the same type as
4212 // BaseType. Therefore, just treat this as a dependent base
4213 // class initialization. FIXME: Should we try to check the
4214 // initialization anyway? It seems odd.
4215 if (ClassDecl->hasAnyDependentBases())
4216 Dependent = true;
4217 else
4218 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4219 << BaseType << Context.getTypeDeclType(ClassDecl)
4220 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4221 }
4222 }
4223
4224 if (Dependent) {
4225 DiscardCleanupsInEvaluationContext();
4226
4227 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4228 /*IsVirtual=*/false,
4229 InitRange.getBegin(), Init,
4230 InitRange.getEnd(), EllipsisLoc);
4231 }
4232
4233 // C++ [base.class.init]p2:
4234 // If a mem-initializer-id is ambiguous because it designates both
4235 // a direct non-virtual base class and an inherited virtual base
4236 // class, the mem-initializer is ill-formed.
4237 if (DirectBaseSpec && VirtualBaseSpec)
4238 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4239 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4240
4241 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4242 if (!BaseSpec)
4243 BaseSpec = VirtualBaseSpec;
4244
4245 // Initialize the base.
4246 bool InitList = true;
4247 MultiExprArg Args = Init;
4248 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4249 InitList = false;
4250 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4251 }
4252
4253 InitializedEntity BaseEntity =
4254 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4255 InitializationKind Kind =
4256 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4257 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4258 InitRange.getEnd());
4259 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4260 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4261 if (BaseInit.isInvalid())
4262 return true;
4263
4264 // C++11 [class.base.init]p7:
4265 // The initialization of each base and member constitutes a
4266 // full-expression.
4267 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4268 /*DiscardedValue*/ false);
4269 if (BaseInit.isInvalid())
4270 return true;
4271
4272 // If we are in a dependent context, template instantiation will
4273 // perform this type-checking again. Just save the arguments that we
4274 // received in a ParenListExpr.
4275 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4276 // of the information that we have about the base
4277 // initializer. However, deconstructing the ASTs is a dicey process,
4278 // and this approach is far more likely to get the corner cases right.
4279 if (CurContext->isDependentContext())
4280 BaseInit = Init;
4281
4282 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4283 BaseSpec->isVirtual(),
4284 InitRange.getBegin(),
4285 BaseInit.getAs<Expr>(),
4286 InitRange.getEnd(), EllipsisLoc);
4287}
4288
4289// Create a static_cast\<T&&>(expr).
4290static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4291 if (T.isNull()) T = E->getType();
4292 QualType TargetType = SemaRef.BuildReferenceType(
4293 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4294 SourceLocation ExprLoc = E->getBeginLoc();
4295 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4296 TargetType, ExprLoc);
4297
4298 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4299 SourceRange(ExprLoc, ExprLoc),
4300 E->getSourceRange()).get();
4301}
4302
4303/// ImplicitInitializerKind - How an implicit base or member initializer should
4304/// initialize its base or member.
4305enum ImplicitInitializerKind {
4306 IIK_Default,
4307 IIK_Copy,
4308 IIK_Move,
4309 IIK_Inherit
4310};
4311
4312static bool
4313BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4314 ImplicitInitializerKind ImplicitInitKind,
4315 CXXBaseSpecifier *BaseSpec,
4316 bool IsInheritedVirtualBase,
4317 CXXCtorInitializer *&CXXBaseInit) {
4318 InitializedEntity InitEntity
4319 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4320 IsInheritedVirtualBase);
4321
4322 ExprResult BaseInit;
4323
4324 switch (ImplicitInitKind) {
4325 case IIK_Inherit:
4326 case IIK_Default: {
4327 InitializationKind InitKind
4328 = InitializationKind::CreateDefault(Constructor->getLocation());
4329 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4330 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4331 break;
4332 }
4333
4334 case IIK_Move:
4335 case IIK_Copy: {
4336 bool Moving = ImplicitInitKind == IIK_Move;
4337 ParmVarDecl *Param = Constructor->getParamDecl(0);
4338 QualType ParamType = Param->getType().getNonReferenceType();
4339
4340 Expr *CopyCtorArg =
4341 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4342 SourceLocation(), Param, false,
4343 Constructor->getLocation(), ParamType,
4344 VK_LValue, nullptr);
4345
4346 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4347
4348 // Cast to the base class to avoid ambiguities.
4349 QualType ArgTy =
4350 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4351 ParamType.getQualifiers());
4352
4353 if (Moving) {
4354 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4355 }
4356
4357 CXXCastPath BasePath;
4358 BasePath.push_back(BaseSpec);
4359 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4360 CK_UncheckedDerivedToBase,
4361 Moving ? VK_XValue : VK_LValue,
4362 &BasePath).get();
4363
4364 InitializationKind InitKind
4365 = InitializationKind::CreateDirect(Constructor->getLocation(),
4366 SourceLocation(), SourceLocation());
4367 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4368 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4369 break;
4370 }
4371 }
4372
4373 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4374 if (BaseInit.isInvalid())
4375 return true;
4376
4377 CXXBaseInit =
4378 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4379 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4380 SourceLocation()),
4381 BaseSpec->isVirtual(),
4382 SourceLocation(),
4383 BaseInit.getAs<Expr>(),
4384 SourceLocation(),
4385 SourceLocation());
4386
4387 return false;
4388}
4389
4390static bool RefersToRValueRef(Expr *MemRef) {
4391 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4392 return Referenced->getType()->isRValueReferenceType();
4393}
4394
4395static bool
4396BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4397 ImplicitInitializerKind ImplicitInitKind,
4398 FieldDecl *Field, IndirectFieldDecl *Indirect,
4399 CXXCtorInitializer *&CXXMemberInit) {
4400 if (Field->isInvalidDecl())
4401 return true;
4402
4403 SourceLocation Loc = Constructor->getLocation();
4404
4405 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4406 bool Moving = ImplicitInitKind == IIK_Move;
4407 ParmVarDecl *Param = Constructor->getParamDecl(0);
4408 QualType ParamType = Param->getType().getNonReferenceType();
4409
4410 // Suppress copying zero-width bitfields.
4411 if (Field->isZeroLengthBitField(SemaRef.Context))
4412 return false;
4413
4414 Expr *MemberExprBase =
4415 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4416 SourceLocation(), Param, false,
4417 Loc, ParamType, VK_LValue, nullptr);
4418
4419 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4420
4421 if (Moving) {
4422 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4423 }
4424
4425 // Build a reference to this field within the parameter.
4426 CXXScopeSpec SS;
4427 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4428 Sema::LookupMemberName);
4429 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4430 : cast<ValueDecl>(Field), AS_public);
4431 MemberLookup.resolveKind();
4432 ExprResult CtorArg
4433 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4434 ParamType, Loc,
4435 /*IsArrow=*/false,
4436 SS,
4437 /*TemplateKWLoc=*/SourceLocation(),
4438 /*FirstQualifierInScope=*/nullptr,
4439 MemberLookup,
4440 /*TemplateArgs=*/nullptr,
4441 /*S*/nullptr);
4442 if (CtorArg.isInvalid())
4443 return true;
4444
4445 // C++11 [class.copy]p15:
4446 // - if a member m has rvalue reference type T&&, it is direct-initialized
4447 // with static_cast<T&&>(x.m);
4448 if (RefersToRValueRef(CtorArg.get())) {
4449 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4450 }
4451
4452 InitializedEntity Entity =
4453 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4454 /*Implicit*/ true)
4455 : InitializedEntity::InitializeMember(Field, nullptr,
4456 /*Implicit*/ true);
4457
4458 // Direct-initialize to use the copy constructor.
4459 InitializationKind InitKind =
4460 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4461
4462 Expr *CtorArgE = CtorArg.getAs<Expr>();
4463 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4464 ExprResult MemberInit =
4465 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4466 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4467 if (MemberInit.isInvalid())
4468 return true;
4469
4470 if (Indirect)
4471 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4472 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4473 else
4474 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4475 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4476 return false;
4477 }
4478
4479 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4480 "Unhandled implicit init kind!");
4481
4482 QualType FieldBaseElementType =
4483 SemaRef.Context.getBaseElementType(Field->getType());
4484
4485 if (FieldBaseElementType->isRecordType()) {
4486 InitializedEntity InitEntity =
4487 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4488 /*Implicit*/ true)
4489 : InitializedEntity::InitializeMember(Field, nullptr,
4490 /*Implicit*/ true);
4491 InitializationKind InitKind =
4492 InitializationKind::CreateDefault(Loc);
4493
4494 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4495 ExprResult MemberInit =
4496 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4497
4498 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4499 if (MemberInit.isInvalid())
4500 return true;
4501
4502 if (Indirect)
4503 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4504 Indirect, Loc,
4505 Loc,
4506 MemberInit.get(),
4507 Loc);
4508 else
4509 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4510 Field, Loc, Loc,
4511 MemberInit.get(),
4512 Loc);
4513 return false;
4514 }
4515
4516 if (!Field->getParent()->isUnion()) {
4517 if (FieldBaseElementType->isReferenceType()) {
4518 SemaRef.Diag(Constructor->getLocation(),
4519 diag::err_uninitialized_member_in_ctor)
4520 << (int)Constructor->isImplicit()
4521 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4522 << 0 << Field->getDeclName();
4523 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4524 return true;
4525 }
4526
4527 if (FieldBaseElementType.isConstQualified()) {
4528 SemaRef.Diag(Constructor->getLocation(),
4529 diag::err_uninitialized_member_in_ctor)
4530 << (int)Constructor->isImplicit()
4531 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4532 << 1 << Field->getDeclName();
4533 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4534 return true;
4535 }
4536 }
4537
4538 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4539 // ARC and Weak:
4540 // Default-initialize Objective-C pointers to NULL.
4541 CXXMemberInit
4542 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4543 Loc, Loc,
4544 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4545 Loc);
4546 return false;
4547 }
4548
4549 // Nothing to initialize.
4550 CXXMemberInit = nullptr;
4551 return false;
4552}
4553
4554namespace {
4555struct BaseAndFieldInfo {
4556 Sema &S;
4557 CXXConstructorDecl *Ctor;
4558 bool AnyErrorsInInits;
4559 ImplicitInitializerKind IIK;
4560 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4561 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4562 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4563
4564 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4565 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4566 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4567 if (Ctor->getInheritedConstructor())
4568 IIK = IIK_Inherit;
4569 else if (Generated && Ctor->isCopyConstructor())
4570 IIK = IIK_Copy;
4571 else if (Generated && Ctor->isMoveConstructor())
4572 IIK = IIK_Move;
4573 else
4574 IIK = IIK_Default;
4575 }
4576
4577 bool isImplicitCopyOrMove() const {
4578 switch (IIK) {
4579 case IIK_Copy:
4580 case IIK_Move:
4581 return true;
4582
4583 case IIK_Default:
4584 case IIK_Inherit:
4585 return false;
4586 }
4587
4588 llvm_unreachable("Invalid ImplicitInitializerKind!");
4589 }
4590
4591 bool addFieldInitializer(CXXCtorInitializer *Init) {
4592 AllToInit.push_back(Init);
4593
4594 // Check whether this initializer makes the field "used".
4595 if (Init->getInit()->HasSideEffects(S.Context))
4596 S.UnusedPrivateFields.remove(Init->getAnyMember());
4597
4598 return false;
4599 }
4600
4601 bool isInactiveUnionMember(FieldDecl *Field) {
4602 RecordDecl *Record = Field->getParent();
4603 if (!Record->isUnion())
4604 return false;
4605
4606 if (FieldDecl *Active =
4607 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4608 return Active != Field->getCanonicalDecl();
4609
4610 // In an implicit copy or move constructor, ignore any in-class initializer.
4611 if (isImplicitCopyOrMove())
4612 return true;
4613
4614 // If there's no explicit initialization, the field is active only if it
4615 // has an in-class initializer...
4616 if (Field->hasInClassInitializer())
4617 return false;
4618 // ... or it's an anonymous struct or union whose class has an in-class
4619 // initializer.
4620 if (!Field->isAnonymousStructOrUnion())
4621 return true;
4622 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4623 return !FieldRD->hasInClassInitializer();
4624 }
4625
4626 /// Determine whether the given field is, or is within, a union member
4627 /// that is inactive (because there was an initializer given for a different
4628 /// member of the union, or because the union was not initialized at all).
4629 bool isWithinInactiveUnionMember(FieldDecl *Field,
4630 IndirectFieldDecl *Indirect) {
4631 if (!Indirect)
4632 return isInactiveUnionMember(Field);
4633
4634 for (auto *C : Indirect->chain()) {
4635 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4636 if (Field && isInactiveUnionMember(Field))
4637 return true;
4638 }
4639 return false;
4640 }
4641};
4642}
4643
4644/// Determine whether the given type is an incomplete or zero-lenfgth
4645/// array type.
4646static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4647 if (T->isIncompleteArrayType())
4648 return true;
4649
4650 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4651 if (!ArrayT->getSize())
4652 return true;
4653
4654 T = ArrayT->getElementType();
4655 }
4656
4657 return false;
4658}
4659
4660static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4661 FieldDecl *Field,
4662 IndirectFieldDecl *Indirect = nullptr) {
4663 if (Field->isInvalidDecl())
4664 return false;
4665
4666 // Overwhelmingly common case: we have a direct initializer for this field.
4667 if (CXXCtorInitializer *Init =
4668 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4669 return Info.addFieldInitializer(Init);
4670
4671 // C++11 [class.base.init]p8:
4672 // if the entity is a non-static data member that has a
4673 // brace-or-equal-initializer and either
4674 // -- the constructor's class is a union and no other variant member of that
4675 // union is designated by a mem-initializer-id or
4676 // -- the constructor's class is not a union, and, if the entity is a member
4677 // of an anonymous union, no other member of that union is designated by
4678 // a mem-initializer-id,
4679 // the entity is initialized as specified in [dcl.init].
4680 //
4681 // We also apply the same rules to handle anonymous structs within anonymous
4682 // unions.
4683 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4684 return false;
4685
4686 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4687 ExprResult DIE =
4688 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4689 if (DIE.isInvalid())
4690 return true;
4691
4692 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4693 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4694
4695 CXXCtorInitializer *Init;
4696 if (Indirect)
4697 Init = new (SemaRef.Context)
4698 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4699 SourceLocation(), DIE.get(), SourceLocation());
4700 else
4701 Init = new (SemaRef.Context)
4702 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4703 SourceLocation(), DIE.get(), SourceLocation());
4704 return Info.addFieldInitializer(Init);
4705 }
4706
4707 // Don't initialize incomplete or zero-length arrays.
4708 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4709 return false;
4710
4711 // Don't try to build an implicit initializer if there were semantic
4712 // errors in any of the initializers (and therefore we might be
4713 // missing some that the user actually wrote).
4714 if (Info.AnyErrorsInInits)
4715 return false;
4716
4717 CXXCtorInitializer *Init = nullptr;
4718 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4719 Indirect, Init))
4720 return true;
4721
4722 if (!Init)
4723 return false;
4724
4725 return Info.addFieldInitializer(Init);
4726}
4727
4728bool
4729Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4730 CXXCtorInitializer *Initializer) {
4731 assert(Initializer->isDelegatingInitializer());
4732 Constructor->setNumCtorInitializers(1);
4733 CXXCtorInitializer **initializer =
4734 new (Context) CXXCtorInitializer*[1];
4735 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4736 Constructor->setCtorInitializers(initializer);
4737
4738 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4739 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4740 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4741 }
4742
4743 DelegatingCtorDecls.push_back(Constructor);
4744
4745 DiagnoseUninitializedFields(*this, Constructor);
4746
4747 return false;
4748}
4749
4750bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4751 ArrayRef<CXXCtorInitializer *> Initializers) {
4752 if (Constructor->isDependentContext()) {
4753 // Just store the initializers as written, they will be checked during
4754 // instantiation.
4755 if (!Initializers.empty()) {
4756 Constructor->setNumCtorInitializers(Initializers.size());
4757 CXXCtorInitializer **baseOrMemberInitializers =
4758 new (Context) CXXCtorInitializer*[Initializers.size()];
4759 memcpy(baseOrMemberInitializers, Initializers.data(),
4760 Initializers.size() * sizeof(CXXCtorInitializer*));
4761 Constructor->setCtorInitializers(baseOrMemberInitializers);
4762 }
4763
4764 // Let template instantiation know whether we had errors.
4765 if (AnyErrors)
4766 Constructor->setInvalidDecl();
4767
4768 return false;
4769 }
4770
4771 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4772
4773 // We need to build the initializer AST according to order of construction
4774 // and not what user specified in the Initializers list.
4775 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4776 if (!ClassDecl)
4777 return true;
4778
4779 bool HadError = false;
4780
4781 for (unsigned i = 0; i < Initializers.size(); i++) {
4782 CXXCtorInitializer *Member = Initializers[i];
4783
4784 if (Member->isBaseInitializer())
4785 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4786 else {
4787 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4788
4789 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4790 for (auto *C : F->chain()) {
4791 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4792 if (FD && FD->getParent()->isUnion())
4793 Info.ActiveUnionMember.insert(std::make_pair(
4794 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4795 }
4796 } else if (FieldDecl *FD = Member->getMember()) {
4797 if (FD->getParent()->isUnion())
4798 Info.ActiveUnionMember.insert(std::make_pair(
4799 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4800 }
4801 }
4802 }
4803
4804 // Keep track of the direct virtual bases.
4805 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4806 for (auto &I : ClassDecl->bases()) {
4807 if (I.isVirtual())
4808 DirectVBases.insert(&I);
4809 }
4810
4811 // Push virtual bases before others.
4812 for (auto &VBase : ClassDecl->vbases()) {
4813 if (CXXCtorInitializer *Value
4814 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4815 // [class.base.init]p7, per DR257:
4816 // A mem-initializer where the mem-initializer-id names a virtual base
4817 // class is ignored during execution of a constructor of any class that
4818 // is not the most derived class.
4819 if (ClassDecl->isAbstract()) {
4820 // FIXME: Provide a fixit to remove the base specifier. This requires
4821 // tracking the location of the associated comma for a base specifier.
4822 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4823 << VBase.getType() << ClassDecl;
4824 DiagnoseAbstractType(ClassDecl);
4825 }
4826
4827 Info.AllToInit.push_back(Value);
4828 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4829 // [class.base.init]p8, per DR257:
4830 // If a given [...] base class is not named by a mem-initializer-id
4831 // [...] and the entity is not a virtual base class of an abstract
4832 // class, then [...] the entity is default-initialized.
4833 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4834 CXXCtorInitializer *CXXBaseInit;
4835 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4836 &VBase, IsInheritedVirtualBase,
4837 CXXBaseInit)) {
4838 HadError = true;
4839 continue;
4840 }
4841
4842 Info.AllToInit.push_back(CXXBaseInit);
4843 }
4844 }
4845
4846 // Non-virtual bases.
4847 for (auto &Base : ClassDecl->bases()) {
4848 // Virtuals are in the virtual base list and already constructed.
4849 if (Base.isVirtual())
4850 continue;
4851
4852 if (CXXCtorInitializer *Value
4853 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4854 Info.AllToInit.push_back(Value);
4855 } else if (!AnyErrors) {
4856 CXXCtorInitializer *CXXBaseInit;
4857 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4858 &Base, /*IsInheritedVirtualBase=*/false,
4859 CXXBaseInit)) {
4860 HadError = true;
4861 continue;
4862 }
4863
4864 Info.AllToInit.push_back(CXXBaseInit);
4865 }
4866 }
4867
4868 // Fields.
4869 for (auto *Mem : ClassDecl->decls()) {
4870 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4871 // C++ [class.bit]p2:
4872 // A declaration for a bit-field that omits the identifier declares an
4873 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4874 // initialized.
4875 if (F->isUnnamedBitfield())
4876 continue;
4877
4878 // If we're not generating the implicit copy/move constructor, then we'll
4879 // handle anonymous struct/union fields based on their individual
4880 // indirect fields.
4881 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4882 continue;
4883
4884 if (CollectFieldInitializer(*this, Info, F))
4885 HadError = true;
4886 continue;
4887 }
4888
4889 // Beyond this point, we only consider default initialization.
4890 if (Info.isImplicitCopyOrMove())
4891 continue;
4892
4893 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4894 if (F->getType()->isIncompleteArrayType()) {
4895 assert(ClassDecl->hasFlexibleArrayMember() &&
4896 "Incomplete array type is not valid");
4897 continue;
4898 }
4899
4900 // Initialize each field of an anonymous struct individually.
4901 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4902 HadError = true;
4903
4904 continue;
4905 }
4906 }
4907
4908 unsigned NumInitializers = Info.AllToInit.size();
4909 if (NumInitializers > 0) {
4910 Constructor->setNumCtorInitializers(NumInitializers);
4911 CXXCtorInitializer **baseOrMemberInitializers =
4912 new (Context) CXXCtorInitializer*[NumInitializers];
4913 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4914 NumInitializers * sizeof(CXXCtorInitializer*));
4915 Constructor->setCtorInitializers(baseOrMemberInitializers);
4916
4917 // Constructors implicitly reference the base and member
4918 // destructors.
4919 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4920 Constructor->getParent());
4921 }
4922
4923 return HadError;
4924}
4925
4926static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4927 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4928 const RecordDecl *RD = RT->getDecl();
4929 if (RD->isAnonymousStructOrUnion()) {
4930 for (auto *Field : RD->fields())
4931 PopulateKeysForFields(Field, IdealInits);
4932 return;
4933 }
4934 }
4935 IdealInits.push_back(Field->getCanonicalDecl());
4936}
4937
4938static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4939 return Context.getCanonicalType(BaseType).getTypePtr();
4940}
4941
4942static const void *GetKeyForMember(ASTContext &Context,
4943 CXXCtorInitializer *Member) {
4944 if (!Member->isAnyMemberInitializer())
4945 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4946
4947 return Member->getAnyMember()->getCanonicalDecl();
4948}
4949
4950static void DiagnoseBaseOrMemInitializerOrder(
4951 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4952 ArrayRef<CXXCtorInitializer *> Inits) {
4953 if (Constructor->getDeclContext()->isDependentContext())
4954 return;
4955
4956 // Don't check initializers order unless the warning is enabled at the
4957 // location of at least one initializer.
4958 bool ShouldCheckOrder = false;
4959 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4960 CXXCtorInitializer *Init = Inits[InitIndex];
4961 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4962 Init->getSourceLocation())) {
4963 ShouldCheckOrder = true;
4964 break;
4965 }
4966 }
4967 if (!ShouldCheckOrder)
4968 return;
4969
4970 // Build the list of bases and members in the order that they'll
4971 // actually be initialized. The explicit initializers should be in
4972 // this same order but may be missing things.
4973 SmallVector<const void*, 32> IdealInitKeys;
4974
4975 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4976
4977 // 1. Virtual bases.
4978 for (const auto &VBase : ClassDecl->vbases())
4979 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4980
4981 // 2. Non-virtual bases.
4982 for (const auto &Base : ClassDecl->bases()) {
4983 if (Base.isVirtual())
4984 continue;
4985 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4986 }
4987
4988 // 3. Direct fields.
4989 for (auto *Field : ClassDecl->fields()) {
4990 if (Field->isUnnamedBitfield())
4991 continue;
4992
4993 PopulateKeysForFields(Field, IdealInitKeys);
4994 }
4995
4996 unsigned NumIdealInits = IdealInitKeys.size();
4997 unsigned IdealIndex = 0;
4998
4999 CXXCtorInitializer *PrevInit = nullptr;
5000 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5001 CXXCtorInitializer *Init = Inits[InitIndex];
5002 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5003
5004 // Scan forward to try to find this initializer in the idealized
5005 // initializers list.
5006 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5007 if (InitKey == IdealInitKeys[IdealIndex])
5008 break;
5009
5010 // If we didn't find this initializer, it must be because we
5011 // scanned past it on a previous iteration. That can only
5012 // happen if we're out of order; emit a warning.
5013 if (IdealIndex == NumIdealInits && PrevInit) {
5014 Sema::SemaDiagnosticBuilder D =
5015 SemaRef.Diag(PrevInit->getSourceLocation(),
5016 diag::warn_initializer_out_of_order);
5017
5018 if (PrevInit->isAnyMemberInitializer())
5019 D << 0 << PrevInit->getAnyMember()->getDeclName();
5020 else
5021 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5022
5023 if (Init->isAnyMemberInitializer())
5024 D << 0 << Init->getAnyMember()->getDeclName();
5025 else
5026 D << 1 << Init->getTypeSourceInfo()->getType();
5027
5028 // Move back to the initializer's location in the ideal list.
5029 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5030 if (InitKey == IdealInitKeys[IdealIndex])
5031 break;
5032
5033 assert(IdealIndex < NumIdealInits &&
5034 "initializer not found in initializer list");
5035 }
5036
5037 PrevInit = Init;
5038 }
5039}
5040
5041namespace {
5042bool CheckRedundantInit(Sema &S,
5043 CXXCtorInitializer *Init,
5044 CXXCtorInitializer *&PrevInit) {
5045 if (!PrevInit) {
5046 PrevInit = Init;
5047 return false;
5048 }
5049
5050 if (FieldDecl *Field = Init->getAnyMember())
5051 S.Diag(Init->getSourceLocation(),
5052 diag::err_multiple_mem_initialization)
5053 << Field->getDeclName()
5054 << Init->getSourceRange();
5055 else {
5056 const Type *BaseClass = Init->getBaseClass();
5057 assert(BaseClass && "neither field nor base");
5058 S.Diag(Init->getSourceLocation(),
5059 diag::err_multiple_base_initialization)
5060 << QualType(BaseClass, 0)
5061 << Init->getSourceRange();
5062 }
5063 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5064 << 0 << PrevInit->getSourceRange();
5065
5066 return true;
5067}
5068
5069typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5070typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5071
5072bool CheckRedundantUnionInit(Sema &S,
5073 CXXCtorInitializer *Init,
5074 RedundantUnionMap &Unions) {
5075 FieldDecl *Field = Init->getAnyMember();
5076 RecordDecl *Parent = Field->getParent();
5077 NamedDecl *Child = Field;
5078
5079 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5080 if (Parent->isUnion()) {
5081 UnionEntry &En = Unions[Parent];
5082 if (En.first && En.first != Child) {
5083 S.Diag(Init->getSourceLocation(),
5084 diag::err_multiple_mem_union_initialization)
5085 << Field->getDeclName()
5086 << Init->getSourceRange();
5087 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5088 << 0 << En.second->getSourceRange();
5089 return true;
5090 }
5091 if (!En.first) {
5092 En.first = Child;
5093 En.second = Init;
5094 }
5095 if (!Parent->isAnonymousStructOrUnion())
5096 return false;
5097 }
5098
5099 Child = Parent;
5100 Parent = cast<RecordDecl>(Parent->getDeclContext());
5101 }
5102
5103 return false;
5104}
5105}
5106
5107/// ActOnMemInitializers - Handle the member initializers for a constructor.
5108void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5109 SourceLocation ColonLoc,
5110 ArrayRef<CXXCtorInitializer*> MemInits,
5111 bool AnyErrors) {
5112 if (!ConstructorDecl)
5113 return;
5114
5115 AdjustDeclIfTemplate(ConstructorDecl);
5116
5117 CXXConstructorDecl *Constructor
5118 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5119
5120 if (!Constructor) {
5121 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5122 return;
5123 }
5124
5125 // Mapping for the duplicate initializers check.
5126 // For member initializers, this is keyed with a FieldDecl*.
5127 // For base initializers, this is keyed with a Type*.
5128 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5129
5130 // Mapping for the inconsistent anonymous-union initializers check.
5131 RedundantUnionMap MemberUnions;
5132
5133 bool HadError = false;
5134 for (unsigned i = 0; i < MemInits.size(); i++) {
5135 CXXCtorInitializer *Init = MemInits[i];
5136
5137 // Set the source order index.
5138 Init->setSourceOrder(i);
5139
5140 if (Init->isAnyMemberInitializer()) {
5141 const void *Key = GetKeyForMember(Context, Init);
5142 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5143 CheckRedundantUnionInit(*this, Init, MemberUnions))
5144 HadError = true;
5145 } else if (Init->isBaseInitializer()) {
5146 const void *Key = GetKeyForMember(Context, Init);
5147 if (CheckRedundantInit(*this, Init, Members[Key]))
5148 HadError = true;
5149 } else {
5150 assert(Init->isDelegatingInitializer());
5151 // This must be the only initializer
5152 if (MemInits.size() != 1) {
5153 Diag(Init->getSourceLocation(),
5154 diag::err_delegating_initializer_alone)
5155 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5156 // We will treat this as being the only initializer.
5157 }
5158 SetDelegatingInitializer(Constructor, MemInits[i]);
5159 // Return immediately as the initializer is set.
5160 return;
5161 }
5162 }
5163
5164 if (HadError)
5165 return;
5166
5167 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5168
5169 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5170
5171 DiagnoseUninitializedFields(*this, Constructor);
5172}
5173
5174void
5175Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5176 CXXRecordDecl *ClassDecl) {
5177 // Ignore dependent contexts. Also ignore unions, since their members never
5178 // have destructors implicitly called.
5179 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5180 return;
5181
5182 // FIXME: all the access-control diagnostics are positioned on the
5183 // field/base declaration. That's probably good; that said, the
5184 // user might reasonably want to know why the destructor is being
5185 // emitted, and we currently don't say.
5186
5187 // Non-static data members.
5188 for (auto *Field : ClassDecl->fields()) {
5189 if (Field->isInvalidDecl())
5190 continue;
5191
5192 // Don't destroy incomplete or zero-length arrays.
5193 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5194 continue;
5195
5196 QualType FieldType = Context.getBaseElementType(Field->getType());
5197
5198 const RecordType* RT = FieldType->getAs<RecordType>();
5199 if (!RT)
5200 continue;
5201
5202 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5203 if (FieldClassDecl->isInvalidDecl())
5204 continue;
5205 if (FieldClassDecl->hasIrrelevantDestructor())
5206 continue;
5207 // The destructor for an implicit anonymous union member is never invoked.
5208 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5209 continue;
5210
5211 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5212 assert(Dtor && "No dtor found for FieldClassDecl!");
5213 CheckDestructorAccess(Field->getLocation(), Dtor,
5214 PDiag(diag::err_access_dtor_field)
5215 << Field->getDeclName()
5216 << FieldType);
5217
5218 MarkFunctionReferenced(Location, Dtor);
5219 DiagnoseUseOfDecl(Dtor, Location);
5220 }
5221
5222 // We only potentially invoke the destructors of potentially constructed
5223 // subobjects.
5224 bool VisitVirtualBases = !ClassDecl->isAbstract();
5225
5226 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5227
5228 // Bases.
5229 for (const auto &Base : ClassDecl->bases()) {
5230 // Bases are always records in a well-formed non-dependent class.
5231 const RecordType *RT = Base.getType()->getAs<RecordType>();
5232
5233 // Remember direct virtual bases.
5234 if (Base.isVirtual()) {
5235 if (!VisitVirtualBases)
5236 continue;
5237 DirectVirtualBases.insert(RT);
5238 }
5239
5240 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5241 // If our base class is invalid, we probably can't get its dtor anyway.
5242 if (BaseClassDecl->isInvalidDecl())
5243 continue;
5244 if (BaseClassDecl->hasIrrelevantDestructor())
5245 continue;
5246
5247 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5248 assert(Dtor && "No dtor found for BaseClassDecl!");
5249
5250 // FIXME: caret should be on the start of the class name
5251 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5252 PDiag(diag::err_access_dtor_base)
5253 << Base.getType() << Base.getSourceRange(),
5254 Context.getTypeDeclType(ClassDecl));
5255
5256 MarkFunctionReferenced(Location, Dtor);
5257 DiagnoseUseOfDecl(Dtor, Location);
5258 }
5259
5260 if (!VisitVirtualBases)
5261 return;
5262
5263 // Virtual bases.
5264 for (const auto &VBase : ClassDecl->vbases()) {
5265 // Bases are always records in a well-formed non-dependent class.
5266 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5267
5268 // Ignore direct virtual bases.
5269 if (DirectVirtualBases.count(RT))
5270 continue;
5271
5272 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5273 // If our base class is invalid, we probably can't get its dtor anyway.
5274 if (BaseClassDecl->isInvalidDecl())
5275 continue;
5276 if (BaseClassDecl->hasIrrelevantDestructor())
5277 continue;
5278
5279 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5280 assert(Dtor && "No dtor found for BaseClassDecl!");
5281 if (CheckDestructorAccess(
5282 ClassDecl->getLocation(), Dtor,
5283 PDiag(diag::err_access_dtor_vbase)
5284 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5285 Context.getTypeDeclType(ClassDecl)) ==
5286 AR_accessible) {
5287 CheckDerivedToBaseConversion(
5288 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5289 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5290 SourceRange(), DeclarationName(), nullptr);
5291 }
5292
5293 MarkFunctionReferenced(Location, Dtor);
5294 DiagnoseUseOfDecl(Dtor, Location);
5295 }
5296}
5297
5298void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5299 if (!CDtorDecl)
5300 return;
5301
5302 if (CXXConstructorDecl *Constructor
5303 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5304 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5305 DiagnoseUninitializedFields(*this, Constructor);
5306 }
5307}
5308
5309bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5310 if (!getLangOpts().CPlusPlus)
5311 return false;
5312
5313 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5314 if (!RD)
5315 return false;
5316
5317 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5318 // class template specialization here, but doing so breaks a lot of code.
5319
5320 // We can't answer whether something is abstract until it has a
5321 // definition. If it's currently being defined, we'll walk back
5322 // over all the declarations when we have a full definition.
5323 const CXXRecordDecl *Def = RD->getDefinition();
5324 if (!Def || Def->isBeingDefined())
5325 return false;
5326
5327 return RD->isAbstract();
5328}
5329
5330bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5331 TypeDiagnoser &Diagnoser) {
5332 if (!isAbstractType(Loc, T))
5333 return false;
5334
5335 T = Context.getBaseElementType(T);
5336 Diagnoser.diagnose(*this, Loc, T);
5337 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5338 return true;
5339}
5340
5341void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5342 // Check if we've already emitted the list of pure virtual functions
5343 // for this class.
5344 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5345 return;
5346
5347 // If the diagnostic is suppressed, don't emit the notes. We're only
5348 // going to emit them once, so try to attach them to a diagnostic we're
5349 // actually going to show.
5350 if (Diags.isLastDiagnosticIgnored())
5351 return;
5352
5353 CXXFinalOverriderMap FinalOverriders;
5354 RD->getFinalOverriders(FinalOverriders);
5355
5356 // Keep a set of seen pure methods so we won't diagnose the same method
5357 // more than once.
5358 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5359
5360 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5361 MEnd = FinalOverriders.end();
5362 M != MEnd;
5363 ++M) {
5364 for (OverridingMethods::iterator SO = M->second.begin(),
5365 SOEnd = M->second.end();
5366 SO != SOEnd; ++SO) {
5367 // C++ [class.abstract]p4:
5368 // A class is abstract if it contains or inherits at least one
5369 // pure virtual function for which the final overrider is pure
5370 // virtual.
5371
5372 //
5373 if (SO->second.size() != 1)
5374 continue;
5375
5376 if (!SO->second.front().Method->isPure())
5377 continue;
5378
5379 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5380 continue;
5381
5382 Diag(SO->second.front().Method->getLocation(),
5383 diag::note_pure_virtual_function)
5384 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5385 }
5386 }
5387
5388 if (!PureVirtualClassDiagSet)
5389 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5390 PureVirtualClassDiagSet->insert(RD);
5391}
5392
5393namespace {
5394struct AbstractUsageInfo {
5395 Sema &S;
5396 CXXRecordDecl *Record;
5397 CanQualType AbstractType;
5398 bool Invalid;
5399
5400 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5401 : S(S), Record(Record),
5402 AbstractType(S.Context.getCanonicalType(
5403 S.Context.getTypeDeclType(Record))),
5404 Invalid(false) {}
5405
5406 void DiagnoseAbstractType() {
5407 if (Invalid) return;
5408 S.DiagnoseAbstractType(Record);
5409 Invalid = true;
5410 }
5411
5412 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5413};
5414
5415struct CheckAbstractUsage {
5416 AbstractUsageInfo &Info;
5417 const NamedDecl *Ctx;
5418
5419 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5420 : Info(Info), Ctx(Ctx) {}
5421
5422 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5423 switch (TL.getTypeLocClass()) {
5424#define ABSTRACT_TYPELOC(CLASS, PARENT)
5425#define TYPELOC(CLASS, PARENT) \
5426 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5427#include "clang/AST/TypeLocNodes.def"
5428 }
5429 }
5430
5431 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5432 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5433 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5434 if (!TL.getParam(I))
5435 continue;
5436
5437 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5438 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5439 }
5440 }
5441
5442 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5443 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5444 }
5445
5446 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5447 // Visit the type parameters from a permissive context.
5448 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5449 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5450 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5451 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5452 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5453 // TODO: other template argument types?
5454 }
5455 }
5456
5457 // Visit pointee types from a permissive context.
5458#define CheckPolymorphic(Type) \
5459 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5460 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5461 }
5462 CheckPolymorphic(PointerTypeLoc)
5463 CheckPolymorphic(ReferenceTypeLoc)
5464 CheckPolymorphic(MemberPointerTypeLoc)
5465 CheckPolymorphic(BlockPointerTypeLoc)
5466 CheckPolymorphic(AtomicTypeLoc)
5467
5468 /// Handle all the types we haven't given a more specific
5469 /// implementation for above.
5470 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5471 // Every other kind of type that we haven't called out already
5472 // that has an inner type is either (1) sugar or (2) contains that
5473 // inner type in some way as a subobject.
5474 if (TypeLoc Next = TL.getNextTypeLoc())
5475 return Visit(Next, Sel);
5476
5477 // If there's no inner type and we're in a permissive context,
5478 // don't diagnose.
5479 if (Sel == Sema::AbstractNone) return;
5480
5481 // Check whether the type matches the abstract type.
5482 QualType T = TL.getType();
5483 if (T->isArrayType()) {
5484 Sel = Sema::AbstractArrayType;
5485 T = Info.S.Context.getBaseElementType(T);
5486 }
5487 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5488 if (CT != Info.AbstractType) return;
5489
5490 // It matched; do some magic.
5491 if (Sel == Sema::AbstractArrayType) {
5492 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5493 << T << TL.getSourceRange();
5494 } else {
5495 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5496 << Sel << T << TL.getSourceRange();
5497 }
5498 Info.DiagnoseAbstractType();
5499 }
5500};
5501
5502void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5503 Sema::AbstractDiagSelID Sel) {
5504 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5505}
5506
5507}
5508
5509/// Check for invalid uses of an abstract type in a method declaration.
5510static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5511 CXXMethodDecl *MD) {
5512 // No need to do the check on definitions, which require that
5513 // the return/param types be complete.
5514 if (MD->doesThisDeclarationHaveABody())
5515 return;
5516
5517 // For safety's sake, just ignore it if we don't have type source
5518 // information. This should never happen for non-implicit methods,
5519 // but...
5520 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5521 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5522}
5523
5524/// Check for invalid uses of an abstract type within a class definition.
5525static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5526 CXXRecordDecl *RD) {
5527 for (auto *D : RD->decls()) {
5528 if (D->isImplicit()) continue;
5529
5530 // Methods and method templates.
5531 if (isa<CXXMethodDecl>(D)) {
5532 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5533 } else if (isa<FunctionTemplateDecl>(D)) {
5534 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5535 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5536
5537 // Fields and static variables.
5538 } else if (isa<FieldDecl>(D)) {
5539 FieldDecl *FD = cast<FieldDecl>(D);
5540 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5541 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5542 } else if (isa<VarDecl>(D)) {
5543 VarDecl *VD = cast<VarDecl>(D);
5544 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5545 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5546
5547 // Nested classes and class templates.
5548 } else if (isa<CXXRecordDecl>(D)) {
5549 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5550 } else if (isa<ClassTemplateDecl>(D)) {
5551 CheckAbstractClassUsage(Info,
5552 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5553 }
5554 }
5555}
5556
5557static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5558 Attr *ClassAttr = getDLLAttr(Class);
5559 if (!ClassAttr)
5560 return;
5561
5562 assert(ClassAttr->getKind() == attr::DLLExport);
5563
5564 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5565
5566 if (TSK == TSK_ExplicitInstantiationDeclaration)
5567 // Don't go any further if this is just an explicit instantiation
5568 // declaration.
5569 return;
5570
5571 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5572 S.MarkVTableUsed(Class->getLocation(), Class, true);
5573
5574 for (Decl *Member : Class->decls()) {
5575 // Defined static variables that are members of an exported base
5576 // class must be marked export too.
5577 auto *VD = dyn_cast<VarDecl>(Member);
5578 if (VD && Member->getAttr<DLLExportAttr>() &&
5579 VD->getStorageClass() == SC_Static &&
5580 TSK == TSK_ImplicitInstantiation)
5581 S.MarkVariableReferenced(VD->getLocation(), VD);
5582
5583 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5584 if (!MD)
5585 continue;
5586
5587 if (Member->getAttr<DLLExportAttr>()) {
5588 if (MD->isUserProvided()) {
5589 // Instantiate non-default class member functions ...
5590
5591 // .. except for certain kinds of template specializations.
5592 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5593 continue;
5594
5595 S.MarkFunctionReferenced(Class->getLocation(), MD);
5596
5597 // The function will be passed to the consumer when its definition is
5598 // encountered.
5599 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5600 MD->isCopyAssignmentOperator() ||
5601 MD->isMoveAssignmentOperator()) {
5602 // Synthesize and instantiate non-trivial implicit methods, explicitly
5603 // defaulted methods, and the copy and move assignment operators. The
5604 // latter are exported even if they are trivial, because the address of
5605 // an operator can be taken and should compare equal across libraries.
5606 DiagnosticErrorTrap Trap(S.Diags);
5607 S.MarkFunctionReferenced(Class->getLocation(), MD);
5608 if (Trap.hasErrorOccurred()) {
5609 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5610 << Class << !S.getLangOpts().CPlusPlus11;
5611 break;
5612 }
5613
5614 // There is no later point when we will see the definition of this
5615 // function, so pass it to the consumer now.
5616 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5617 }
5618 }
5619 }
5620}
5621
5622static void checkForMultipleExportedDefaultConstructors(Sema &S,
5623 CXXRecordDecl *Class) {
5624 // Only the MS ABI has default constructor closures, so we don't need to do
5625 // this semantic checking anywhere else.
5626 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5627 return;
5628
5629 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5630 for (Decl *Member : Class->decls()) {
5631 // Look for exported default constructors.
5632 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5633 if (!CD || !CD->isDefaultConstructor())
5634 continue;
5635 auto *Attr = CD->getAttr<DLLExportAttr>();
5636 if (!Attr)
5637 continue;
5638
5639 // If the class is non-dependent, mark the default arguments as ODR-used so
5640 // that we can properly codegen the constructor closure.
5641 if (!Class->isDependentContext()) {
5642 for (ParmVarDecl *PD : CD->parameters()) {
5643 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5644 S.DiscardCleanupsInEvaluationContext();
5645 }
5646 }
5647
5648 if (LastExportedDefaultCtor) {
5649 S.Diag(LastExportedDefaultCtor->getLocation(),
5650 diag::err_attribute_dll_ambiguous_default_ctor)
5651 << Class;
5652 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5653 << CD->getDeclName();
5654 return;
5655 }
5656 LastExportedDefaultCtor = CD;
5657 }
5658}
5659
5660void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5661 // Mark any compiler-generated routines with the implicit code_seg attribute.
5662 for (auto *Method : Class->methods()) {
5663 if (Method->isUserProvided())
5664 continue;
5665 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5666 Method->addAttr(A);
5667 }
5668}
5669
5670/// Check class-level dllimport/dllexport attribute.
5671void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5672 Attr *ClassAttr = getDLLAttr(Class);
5673
5674 // MSVC inherits DLL attributes to partial class template specializations.
5675 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5676 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5677 if (Attr *TemplateAttr =
5678 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5679 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5680 A->setInherited(true);
5681 ClassAttr = A;
5682 }
5683 }
5684 }
5685
5686 if (!ClassAttr)
5687 return;
5688
5689 if (!Class->isExternallyVisible()) {
5690 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5691 << Class << ClassAttr;
5692 return;
5693 }
5694
5695 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5696 !ClassAttr->isInherited()) {
5697 // Diagnose dll attributes on members of class with dll attribute.
5698 for (Decl *Member : Class->decls()) {
5699 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5700 continue;
5701 InheritableAttr *MemberAttr = getDLLAttr(Member);
5702 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5703 continue;
5704
5705 Diag(MemberAttr->getLocation(),
5706 diag::err_attribute_dll_member_of_dll_class)
5707 << MemberAttr << ClassAttr;
5708 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5709 Member->setInvalidDecl();
5710 }
5711 }
5712
5713 if (Class->getDescribedClassTemplate())
5714 // Don't inherit dll attribute until the template is instantiated.
5715 return;
5716
5717 // The class is either imported or exported.
5718 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5719
5720 // Check if this was a dllimport attribute propagated from a derived class to
5721 // a base class template specialization. We don't apply these attributes to
5722 // static data members.
5723 const bool PropagatedImport =
5724 !ClassExported &&
5725 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5726
5727 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5728
5729 // Ignore explicit dllexport on explicit class template instantiation
5730 // declarations, except in MinGW mode.
5731 if (ClassExported && !ClassAttr->isInherited() &&
5732 TSK == TSK_ExplicitInstantiationDeclaration &&
5733 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5734 Class->dropAttr<DLLExportAttr>();
5735 return;
5736 }
5737
5738 // Force declaration of implicit members so they can inherit the attribute.
5739 ForceDeclarationOfImplicitMembers(Class);
5740
5741 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5742 // seem to be true in practice?
5743
5744 for (Decl *Member : Class->decls()) {
5745 VarDecl *VD = dyn_cast<VarDecl>(Member);
5746 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5747
5748 // Only methods and static fields inherit the attributes.
5749 if (!VD && !MD)
5750 continue;
5751
5752 if (MD) {
5753 // Don't process deleted methods.
5754 if (MD->isDeleted())
5755 continue;
5756
5757 if (MD->isInlined()) {
5758 // MinGW does not import or export inline methods. But do it for
5759 // template instantiations.
5760 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5761 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5762 TSK != TSK_ExplicitInstantiationDeclaration &&
5763 TSK != TSK_ExplicitInstantiationDefinition)
5764 continue;
5765
5766 // MSVC versions before 2015 don't export the move assignment operators
5767 // and move constructor, so don't attempt to import/export them if
5768 // we have a definition.
5769 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5770 if ((MD->isMoveAssignmentOperator() ||
5771 (Ctor && Ctor->isMoveConstructor())) &&
5772 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5773 continue;
5774
5775 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5776 // operator is exported anyway.
5777 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5778 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5779 continue;
5780 }
5781 }
5782
5783 // Don't apply dllimport attributes to static data members of class template
5784 // instantiations when the attribute is propagated from a derived class.
5785 if (VD && PropagatedImport)
5786 continue;
5787
5788 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5789 continue;
5790
5791 if (!getDLLAttr(Member)) {
5792 InheritableAttr *NewAttr = nullptr;
5793
5794 // Do not export/import inline function when -fno-dllexport-inlines is
5795 // passed. But add attribute for later local static var check.
5796 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5797 TSK != TSK_ExplicitInstantiationDeclaration &&
5798 TSK != TSK_ExplicitInstantiationDefinition) {
5799 if (ClassExported) {
5800 NewAttr = ::new (getASTContext())
5801 DLLExportStaticLocalAttr(ClassAttr->getRange(),
5802 getASTContext(),
5803 ClassAttr->getSpellingListIndex());
5804 } else {
5805 NewAttr = ::new (getASTContext())
5806 DLLImportStaticLocalAttr(ClassAttr->getRange(),
5807 getASTContext(),
5808 ClassAttr->getSpellingListIndex());
5809 }
5810 } else {
5811 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5812 }
5813
5814 NewAttr->setInherited(true);
5815 Member->addAttr(NewAttr);
5816
5817 if (MD) {
5818 // Propagate DLLAttr to friend re-declarations of MD that have already
5819 // been constructed.
5820 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5821 FD = FD->getPreviousDecl()) {
5822 if (FD->getFriendObjectKind() == Decl::FOK_None)
5823 continue;
5824 assert(!getDLLAttr(FD) &&
5825 "friend re-decl should not already have a DLLAttr");
5826 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5827 NewAttr->setInherited(true);
5828 FD->addAttr(NewAttr);
5829 }
5830 }
5831 }
5832 }
5833
5834 if (ClassExported)
5835 DelayedDllExportClasses.push_back(Class);
5836}
5837
5838/// Perform propagation of DLL attributes from a derived class to a
5839/// templated base class for MS compatibility.
5840void Sema::propagateDLLAttrToBaseClassTemplate(
5841 CXXRecordDecl *Class, Attr *ClassAttr,
5842 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5843 if (getDLLAttr(
5844 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5845 // If the base class template has a DLL attribute, don't try to change it.
5846 return;
5847 }
5848
5849 auto TSK = BaseTemplateSpec->getSpecializationKind();
5850 if (!getDLLAttr(BaseTemplateSpec) &&
5851 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5852 TSK == TSK_ImplicitInstantiation)) {
5853 // The template hasn't been instantiated yet (or it has, but only as an
5854 // explicit instantiation declaration or implicit instantiation, which means
5855 // we haven't codegenned any members yet), so propagate the attribute.
5856 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5857 NewAttr->setInherited(true);
5858 BaseTemplateSpec->addAttr(NewAttr);
5859
5860 // If this was an import, mark that we propagated it from a derived class to
5861 // a base class template specialization.
5862 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5863 ImportAttr->setPropagatedToBaseTemplate();
5864
5865 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5866 // needs to be run again to work see the new attribute. Otherwise this will
5867 // get run whenever the template is instantiated.
5868 if (TSK != TSK_Undeclared)
5869 checkClassLevelDLLAttribute(BaseTemplateSpec);
5870
5871 return;
5872 }
5873
5874 if (getDLLAttr(BaseTemplateSpec)) {
5875 // The template has already been specialized or instantiated with an
5876 // attribute, explicitly or through propagation. We should not try to change
5877 // it.
5878 return;
5879 }
5880
5881 // The template was previously instantiated or explicitly specialized without
5882 // a dll attribute, It's too late for us to add an attribute, so warn that
5883 // this is unsupported.
5884 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5885 << BaseTemplateSpec->isExplicitSpecialization();
5886 Diag(ClassAttr->getLocation(), diag::note_attribute);
5887 if (BaseTemplateSpec->isExplicitSpecialization()) {
5888 Diag(BaseTemplateSpec->getLocation(),
5889 diag::note_template_class_explicit_specialization_was_here)
5890 << BaseTemplateSpec;
5891 } else {
5892 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5893 diag::note_template_class_instantiation_was_here)
5894 << BaseTemplateSpec;
5895 }
5896}
5897
5898static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5899 SourceLocation DefaultLoc) {
5900 switch (S.getSpecialMember(MD)) {
5901 case Sema::CXXDefaultConstructor:
5902 S.DefineImplicitDefaultConstructor(DefaultLoc,
5903 cast<CXXConstructorDecl>(MD));
5904 break;
5905 case Sema::CXXCopyConstructor:
5906 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5907 break;
5908 case Sema::CXXCopyAssignment:
5909 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5910 break;
5911 case Sema::CXXDestructor:
5912 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5913 break;
5914 case Sema::CXXMoveConstructor:
5915 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5916 break;
5917 case Sema::CXXMoveAssignment:
5918 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5919 break;
5920 case Sema::CXXInvalid:
5921 llvm_unreachable("Invalid special member.");
5922 }
5923}
5924
5925/// Determine whether a type is permitted to be passed or returned in
5926/// registers, per C++ [class.temporary]p3.
5927static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5928 TargetInfo::CallingConvKind CCK) {
5929 if (D->isDependentType() || D->isInvalidDecl())
5930 return false;
5931
5932 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5933 // The PS4 platform ABI follows the behavior of Clang 3.2.
5934 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5935 return !D->hasNonTrivialDestructorForCall() &&
5936 !D->hasNonTrivialCopyConstructorForCall();
5937
5938 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5939 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5940 bool DtorIsTrivialForCall = false;
5941
5942 // If a class has at least one non-deleted, trivial copy constructor, it
5943 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5944 //
5945 // Note: This permits classes with non-trivial copy or move ctors to be
5946 // passed in registers, so long as they *also* have a trivial copy ctor,
5947 // which is non-conforming.
5948 if (D->needsImplicitCopyConstructor()) {
5949 if (!D->defaultedCopyConstructorIsDeleted()) {
5950 if (D->hasTrivialCopyConstructor())
5951 CopyCtorIsTrivial = true;
5952 if (D->hasTrivialCopyConstructorForCall())
5953 CopyCtorIsTrivialForCall = true;
5954 }
5955 } else {
5956 for (const CXXConstructorDecl *CD : D->ctors()) {
5957 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5958 if (CD->isTrivial())
5959 CopyCtorIsTrivial = true;
5960 if (CD->isTrivialForCall())
5961 CopyCtorIsTrivialForCall = true;
5962 }
5963 }
5964 }
5965
5966 if (D->needsImplicitDestructor()) {
5967 if (!D->defaultedDestructorIsDeleted() &&
5968 D->hasTrivialDestructorForCall())
5969 DtorIsTrivialForCall = true;
5970 } else if (const auto *DD = D->getDestructor()) {
5971 if (!DD->isDeleted() && DD->isTrivialForCall())
5972 DtorIsTrivialForCall = true;
5973 }
5974
5975 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5976 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5977 return true;
5978
5979 // If a class has a destructor, we'd really like to pass it indirectly
5980 // because it allows us to elide copies. Unfortunately, MSVC makes that
5981 // impossible for small types, which it will pass in a single register or
5982 // stack slot. Most objects with dtors are large-ish, so handle that early.
5983 // We can't call out all large objects as being indirect because there are
5984 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5985 // how we pass large POD types.
5986
5987 // Note: This permits small classes with nontrivial destructors to be
5988 // passed in registers, which is non-conforming.
5989 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5990 uint64_t TypeSize = isAArch64 ? 128 : 64;
5991
5992 if (CopyCtorIsTrivial &&
5993 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5994 return true;
5995 return false;
5996 }
5997
5998 // Per C++ [class.temporary]p3, the relevant condition is:
5999 // each copy constructor, move constructor, and destructor of X is
6000 // either trivial or deleted, and X has at least one non-deleted copy
6001 // or move constructor
6002 bool HasNonDeletedCopyOrMove = false;
6003
6004 if (D->needsImplicitCopyConstructor() &&
6005 !D->defaultedCopyConstructorIsDeleted()) {
6006 if (!D->hasTrivialCopyConstructorForCall())
6007 return false;
6008 HasNonDeletedCopyOrMove = true;
6009 }
6010
6011 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6012 !D->defaultedMoveConstructorIsDeleted()) {
6013 if (!D->hasTrivialMoveConstructorForCall())
6014 return false;
6015 HasNonDeletedCopyOrMove = true;
6016 }
6017
6018 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6019 !D->hasTrivialDestructorForCall())
6020 return false;
6021
6022 for (const CXXMethodDecl *MD : D->methods()) {
6023 if (MD->isDeleted())
6024 continue;
6025
6026 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6027 if (CD && CD->isCopyOrMoveConstructor())
6028 HasNonDeletedCopyOrMove = true;
6029 else if (!isa<CXXDestructorDecl>(MD))
6030 continue;
6031
6032 if (!MD->isTrivialForCall())
6033 return false;
6034 }
6035
6036 return HasNonDeletedCopyOrMove;
6037}
6038
6039/// Perform semantic checks on a class definition that has been
6040/// completing, introducing implicitly-declared members, checking for
6041/// abstract types, etc.
6042void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6043 if (!Record)
6044 return;
6045
6046 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6047 AbstractUsageInfo Info(*this, Record);
6048 CheckAbstractClassUsage(Info, Record);
6049 }
6050
6051 // If this is not an aggregate type and has no user-declared constructor,
6052 // complain about any non-static data members of reference or const scalar
6053 // type, since they will never get initializers.
6054 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6055 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6056 !Record->isLambda()) {
6057 bool Complained = false;
6058 for (const auto *F : Record->fields()) {
6059 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6060 continue;
6061
6062 if (F->getType()->isReferenceType() ||
6063 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6064 if (!Complained) {
6065 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6066 << Record->getTagKind() << Record;
6067 Complained = true;
6068 }
6069
6070 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6071 << F->getType()->isReferenceType()
6072 << F->getDeclName();
6073 }
6074 }
6075 }
6076
6077 if (Record->getIdentifier()) {
6078 // C++ [class.mem]p13:
6079 // If T is the name of a class, then each of the following shall have a
6080 // name different from T:
6081 // - every member of every anonymous union that is a member of class T.
6082 //
6083 // C++ [class.mem]p14:
6084 // In addition, if class T has a user-declared constructor (12.1), every
6085 // non-static data member of class T shall have a name different from T.
6086 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6087 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6088 ++I) {
6089 NamedDecl *D = (*I)->getUnderlyingDecl();
6090 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6091 Record->hasUserDeclaredConstructor()) ||
6092 isa<IndirectFieldDecl>(D)) {
6093 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6094 << D->getDeclName();
6095 break;
6096 }
6097 }
6098 }
6099
6100 // Warn if the class has virtual methods but non-virtual public destructor.
6101 if (Record->isPolymorphic() && !Record->isDependentType()) {
6102 CXXDestructorDecl *dtor = Record->getDestructor();
6103 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6104 !Record->hasAttr<FinalAttr>())
6105 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6106 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6107 }
6108
6109 if (Record->isAbstract()) {
6110 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6111 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6112 << FA->isSpelledAsSealed();
6113 DiagnoseAbstractType(Record);
6114 }
6115 }
6116
6117 // See if trivial_abi has to be dropped.
6118 if (Record->hasAttr<TrivialABIAttr>())
6119 checkIllFormedTrivialABIStruct(*Record);
6120
6121 // Set HasTrivialSpecialMemberForCall if the record has attribute
6122 // "trivial_abi".
6123 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6124
6125 if (HasTrivialABI)
6126 Record->setHasTrivialSpecialMemberForCall();
6127
6128 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6129 // Check whether the explicitly-defaulted special members are valid.
6130 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6131 CheckExplicitlyDefaultedSpecialMember(M);
6132
6133 // For an explicitly defaulted or deleted special member, we defer
6134 // determining triviality until the class is complete. That time is now!
6135 CXXSpecialMember CSM = getSpecialMember(M);
6136 if (!M->isImplicit() && !M->isUserProvided()) {
6137 if (CSM != CXXInvalid) {
6138 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6139 // Inform the class that we've finished declaring this member.
6140 Record->finishedDefaultedOrDeletedMember(M);
6141 M->setTrivialForCall(
6142 HasTrivialABI ||
6143 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6144 Record->setTrivialForCallFlags(M);
6145 }
6146 }
6147
6148 // Set triviality for the purpose of calls if this is a user-provided
6149 // copy/move constructor or destructor.
6150 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6151 CSM == CXXDestructor) && M->isUserProvided()) {
6152 M->setTrivialForCall(HasTrivialABI);
6153 Record->setTrivialForCallFlags(M);
6154 }
6155
6156 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6157 M->hasAttr<DLLExportAttr>()) {
6158 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6159 M->isTrivial() &&
6160 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6161 CSM == CXXDestructor))
6162 M->dropAttr<DLLExportAttr>();
6163
6164 if (M->hasAttr<DLLExportAttr>()) {
6165 DefineImplicitSpecialMember(*this, M, M->getLocation());
6166 ActOnFinishInlineFunctionDef(M);
6167 }
6168 }
6169 };
6170
6171 bool HasMethodWithOverrideControl = false,
6172 HasOverridingMethodWithoutOverrideControl = false;
6173 if (!Record->isDependentType()) {
6174 // Check the destructor before any other member function. We need to
6175 // determine whether it's trivial in order to determine whether the claas
6176 // type is a literal type, which is a prerequisite for determining whether
6177 // other special member functions are valid and whether they're implicitly
6178 // 'constexpr'.
6179 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6180 CompleteMemberFunction(Dtor);
6181
6182 for (auto *M : Record->methods()) {
6183 // See if a method overloads virtual methods in a base
6184 // class without overriding any.
6185 if (!M->isStatic())
6186 DiagnoseHiddenVirtualMethods(M);
6187 if (M->hasAttr<OverrideAttr>())
6188 HasMethodWithOverrideControl = true;
6189 else if (M->size_overridden_methods() > 0)
6190 HasOverridingMethodWithoutOverrideControl = true;
6191
6192 if (!isa<CXXDestructorDecl>(M))
6193 CompleteMemberFunction(M);
6194 }
6195 }
6196
6197 if (HasMethodWithOverrideControl &&
6198 HasOverridingMethodWithoutOverrideControl) {
6199 // At least one method has the 'override' control declared.
6200 // Diagnose all other overridden methods which do not have 'override' specified on them.
6201 for (auto *M : Record->methods())
6202 DiagnoseAbsenceOfOverrideControl(M);
6203 }
6204
6205 // ms_struct is a request to use the same ABI rules as MSVC. Check
6206 // whether this class uses any C++ features that are implemented
6207 // completely differently in MSVC, and if so, emit a diagnostic.
6208 // That diagnostic defaults to an error, but we allow projects to
6209 // map it down to a warning (or ignore it). It's a fairly common
6210 // practice among users of the ms_struct pragma to mass-annotate
6211 // headers, sweeping up a bunch of types that the project doesn't
6212 // really rely on MSVC-compatible layout for. We must therefore
6213 // support "ms_struct except for C++ stuff" as a secondary ABI.
6214 if (Record->isMsStruct(Context) &&
6215 (Record->isPolymorphic() || Record->getNumBases())) {
6216 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6217 }
6218
6219 checkClassLevelDLLAttribute(Record);
6220 checkClassLevelCodeSegAttribute(Record);
6221
6222 bool ClangABICompat4 =
6223 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6224 TargetInfo::CallingConvKind CCK =
6225 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6226 bool CanPass = canPassInRegisters(*this, Record, CCK);
6227
6228 // Do not change ArgPassingRestrictions if it has already been set to
6229 // APK_CanNeverPassInRegs.
6230 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6231 Record->setArgPassingRestrictions(CanPass
6232 ? RecordDecl::APK_CanPassInRegs
6233 : RecordDecl::APK_CannotPassInRegs);
6234
6235 // If canPassInRegisters returns true despite the record having a non-trivial
6236 // destructor, the record is destructed in the callee. This happens only when
6237 // the record or one of its subobjects has a field annotated with trivial_abi
6238 // or a field qualified with ObjC __strong/__weak.
6239 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6240 Record->setParamDestroyedInCallee(true);
6241 else if (Record->hasNonTrivialDestructor())
6242 Record->setParamDestroyedInCallee(CanPass);
6243
6244 if (getLangOpts().ForceEmitVTables) {
6245 // If we want to emit all the vtables, we need to mark it as used. This
6246 // is especially required for cases like vtable assumption loads.
6247 MarkVTableUsed(Record->getInnerLocStart(), Record);
6248 }
6249}
6250
6251/// Look up the special member function that would be called by a special
6252/// member function for a subobject of class type.
6253///
6254/// \param Class The class type of the subobject.
6255/// \param CSM The kind of special member function.
6256/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6257/// \param ConstRHS True if this is a copy operation with a const object
6258/// on its RHS, that is, if the argument to the outer special member
6259/// function is 'const' and this is not a field marked 'mutable'.
6260static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6261 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6262 unsigned FieldQuals, bool ConstRHS) {
6263 unsigned LHSQuals = 0;
6264 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6265 LHSQuals = FieldQuals;
6266
6267 unsigned RHSQuals = FieldQuals;
6268 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6269 RHSQuals = 0;
6270 else if (ConstRHS)
6271 RHSQuals |= Qualifiers::Const;
6272
6273 return S.LookupSpecialMember(Class, CSM,
6274 RHSQuals & Qualifiers::Const,
6275 RHSQuals & Qualifiers::Volatile,
6276 false,
6277 LHSQuals & Qualifiers::Const,
6278 LHSQuals & Qualifiers::Volatile);
6279}
6280
6281class Sema::InheritedConstructorInfo {
6282 Sema &S;
6283 SourceLocation UseLoc;
6284
6285 /// A mapping from the base classes through which the constructor was
6286 /// inherited to the using shadow declaration in that base class (or a null
6287 /// pointer if the constructor was declared in that base class).
6288 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6289 InheritedFromBases;
6290
6291public:
6292 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6293 ConstructorUsingShadowDecl *Shadow)
6294 : S(S), UseLoc(UseLoc) {
6295 bool DiagnosedMultipleConstructedBases = false;
6296 CXXRecordDecl *ConstructedBase = nullptr;
6297 UsingDecl *ConstructedBaseUsing = nullptr;
6298
6299 // Find the set of such base class subobjects and check that there's a
6300 // unique constructed subobject.
6301 for (auto *D : Shadow->redecls()) {
6302 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6303 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6304 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6305
6306 InheritedFromBases.insert(
6307 std::make_pair(DNominatedBase->getCanonicalDecl(),
6308 DShadow->getNominatedBaseClassShadowDecl()));
6309 if (DShadow->constructsVirtualBase())
6310 InheritedFromBases.insert(
6311 std::make_pair(DConstructedBase->getCanonicalDecl(),
6312 DShadow->getConstructedBaseClassShadowDecl()));
6313 else
6314 assert(DNominatedBase == DConstructedBase);
6315
6316 // [class.inhctor.init]p2:
6317 // If the constructor was inherited from multiple base class subobjects
6318 // of type B, the program is ill-formed.
6319 if (!ConstructedBase) {
6320 ConstructedBase = DConstructedBase;
6321 ConstructedBaseUsing = D->getUsingDecl();
6322 } else if (ConstructedBase != DConstructedBase &&
6323 !Shadow->isInvalidDecl()) {
6324 if (!DiagnosedMultipleConstructedBases) {
6325 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6326 << Shadow->getTargetDecl();
6327 S.Diag(ConstructedBaseUsing->getLocation(),
6328 diag::note_ambiguous_inherited_constructor_using)
6329 << ConstructedBase;
6330 DiagnosedMultipleConstructedBases = true;
6331 }
6332 S.Diag(D->getUsingDecl()->getLocation(),
6333 diag::note_ambiguous_inherited_constructor_using)
6334 << DConstructedBase;
6335 }
6336 }
6337
6338 if (DiagnosedMultipleConstructedBases)
6339 Shadow->setInvalidDecl();
6340 }
6341
6342 /// Find the constructor to use for inherited construction of a base class,
6343 /// and whether that base class constructor inherits the constructor from a
6344 /// virtual base class (in which case it won't actually invoke it).
6345 std::pair<CXXConstructorDecl *, bool>
6346 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6347 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6348 if (It == InheritedFromBases.end())
6349 return std::make_pair(nullptr, false);
6350
6351 // This is an intermediary class.
6352 if (It->second)
6353 return std::make_pair(
6354 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6355 It->second->constructsVirtualBase());
6356
6357 // This is the base class from which the constructor was inherited.
6358 return std::make_pair(Ctor, false);
6359 }
6360};
6361
6362/// Is the special member function which would be selected to perform the
6363/// specified operation on the specified class type a constexpr constructor?
6364static bool
6365specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6366 Sema::CXXSpecialMember CSM, unsigned Quals,
6367 bool ConstRHS,
6368 CXXConstructorDecl *InheritedCtor = nullptr,
6369 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6370 // If we're inheriting a constructor, see if we need to call it for this base
6371 // class.
6372 if (InheritedCtor) {
6373 assert(CSM == Sema::CXXDefaultConstructor);
6374 auto BaseCtor =
6375 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6376 if (BaseCtor)
6377 return BaseCtor->isConstexpr();
6378 }
6379
6380 if (CSM == Sema::CXXDefaultConstructor)
6381 return ClassDecl->hasConstexprDefaultConstructor();
6382
6383 Sema::SpecialMemberOverloadResult SMOR =
6384 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6385 if (!SMOR.getMethod())
6386 // A constructor we wouldn't select can't be "involved in initializing"
6387 // anything.
6388 return true;
6389 return SMOR.getMethod()->isConstexpr();
6390}
6391
6392/// Determine whether the specified special member function would be constexpr
6393/// if it were implicitly defined.
6394static bool defaultedSpecialMemberIsConstexpr(
6395 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6396 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6397 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6398 if (!S.getLangOpts().CPlusPlus11)
6399 return false;
6400
6401 // C++11 [dcl.constexpr]p4:
6402 // In the definition of a constexpr constructor [...]
6403 bool Ctor = true;
6404 switch (CSM) {
6405 case Sema::CXXDefaultConstructor:
6406 if (Inherited)
6407 break;
6408 // Since default constructor lookup is essentially trivial (and cannot
6409 // involve, for instance, template instantiation), we compute whether a
6410 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6411 //
6412 // This is important for performance; we need to know whether the default
6413 // constructor is constexpr to determine whether the type is a literal type.
6414 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6415
6416 case Sema::CXXCopyConstructor:
6417 case Sema::CXXMoveConstructor:
6418 // For copy or move constructors, we need to perform overload resolution.
6419 break;
6420
6421 case Sema::CXXCopyAssignment:
6422 case Sema::CXXMoveAssignment:
6423 if (!S.getLangOpts().CPlusPlus14)
6424 return false;
6425 // In C++1y, we need to perform overload resolution.
6426 Ctor = false;
6427 break;
6428
6429 case Sema::CXXDestructor:
6430 case Sema::CXXInvalid:
6431 return false;
6432 }
6433
6434 // -- if the class is a non-empty union, or for each non-empty anonymous
6435 // union member of a non-union class, exactly one non-static data member
6436 // shall be initialized; [DR1359]
6437 //
6438 // If we squint, this is guaranteed, since exactly one non-static data member
6439 // will be initialized (if the constructor isn't deleted), we just don't know
6440 // which one.
6441 if (Ctor && ClassDecl->isUnion())
6442 return CSM == Sema::CXXDefaultConstructor
6443 ? ClassDecl->hasInClassInitializer() ||
6444 !ClassDecl->hasVariantMembers()
6445 : true;
6446
6447 // -- the class shall not have any virtual base classes;
6448 if (Ctor && ClassDecl->getNumVBases())
6449 return false;
6450
6451 // C++1y [class.copy]p26:
6452 // -- [the class] is a literal type, and
6453 if (!Ctor && !ClassDecl->isLiteral())
6454 return false;
6455
6456 // -- every constructor involved in initializing [...] base class
6457 // sub-objects shall be a constexpr constructor;
6458 // -- the assignment operator selected to copy/move each direct base
6459 // class is a constexpr function, and
6460 for (const auto &B : ClassDecl->bases()) {
6461 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6462 if (!BaseType) continue;
6463
6464 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6465 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6466 InheritedCtor, Inherited))
6467 return false;
6468 }
6469
6470 // -- every constructor involved in initializing non-static data members
6471 // [...] shall be a constexpr constructor;
6472 // -- every non-static data member and base class sub-object shall be
6473 // initialized
6474 // -- for each non-static data member of X that is of class type (or array
6475 // thereof), the assignment operator selected to copy/move that member is
6476 // a constexpr function
6477 for (const auto *F : ClassDecl->fields()) {
6478 if (F->isInvalidDecl())
6479 continue;
6480 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6481 continue;
6482 QualType BaseType = S.Context.getBaseElementType(F->getType());
6483 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6484 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6485 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6486 BaseType.getCVRQualifiers(),
6487 ConstArg && !F->isMutable()))
6488 return false;
6489 } else if (CSM == Sema::CXXDefaultConstructor) {
6490 return false;
6491 }
6492 }
6493
6494 // All OK, it's constexpr!
6495 return true;
6496}
6497
6498static Sema::ImplicitExceptionSpecification
6499ComputeDefaultedSpecialMemberExceptionSpec(
6500 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6501 Sema::InheritedConstructorInfo *ICI);
6502
6503static Sema::ImplicitExceptionSpecification
6504computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6505 auto CSM = S.getSpecialMember(MD);
6506 if (CSM != Sema::CXXInvalid)
6507 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6508
6509 auto *CD = cast<CXXConstructorDecl>(MD);
6510 assert(CD->getInheritedConstructor() &&
6511 "only special members have implicit exception specs");
6512 Sema::InheritedConstructorInfo ICI(
6513 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6514 return ComputeDefaultedSpecialMemberExceptionSpec(
6515 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6516}
6517
6518static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6519 CXXMethodDecl *MD) {
6520 FunctionProtoType::ExtProtoInfo EPI;
6521
6522 // Build an exception specification pointing back at this member.
6523 EPI.ExceptionSpec.Type = EST_Unevaluated;
6524 EPI.ExceptionSpec.SourceDecl = MD;
6525
6526 // Set the calling convention to the default for C++ instance methods.
6527 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6528 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6529 /*IsCXXMethod=*/true));
6530 return EPI;
6531}
6532
6533void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6534 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6535 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6536 return;
6537
6538 // Evaluate the exception specification.
6539 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6540 auto ESI = IES.getExceptionSpec();
6541
6542 // Update the type of the special member to use it.
6543 UpdateExceptionSpec(MD, ESI);
6544
6545 // A user-provided destructor can be defined outside the class. When that
6546 // happens, be sure to update the exception specification on both
6547 // declarations.
6548 const FunctionProtoType *CanonicalFPT =
6549 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6550 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6551 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6552}
6553
6554void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6555 CXXRecordDecl *RD = MD->getParent();
6556 CXXSpecialMember CSM = getSpecialMember(MD);
6557
6558 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6559 "not an explicitly-defaulted special member");
6560
6561 // Whether this was the first-declared instance of the constructor.
6562 // This affects whether we implicitly add an exception spec and constexpr.
6563 bool First = MD == MD->getCanonicalDecl();
6564
6565 bool HadError = false;
6566
6567 // C++11 [dcl.fct.def.default]p1:
6568 // A function that is explicitly defaulted shall
6569 // -- be a special member function (checked elsewhere),
6570 // -- have the same type (except for ref-qualifiers, and except that a
6571 // copy operation can take a non-const reference) as an implicit
6572 // declaration, and
6573 // -- not have default arguments.
6574 // C++2a changes the second bullet to instead delete the function if it's
6575 // defaulted on its first declaration, unless it's "an assignment operator,
6576 // and its return type differs or its parameter type is not a reference".
6577 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6578 bool ShouldDeleteForTypeMismatch = false;
6579 unsigned ExpectedParams = 1;
6580 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6581 ExpectedParams = 0;
6582 if (MD->getNumParams() != ExpectedParams) {
6583 // This checks for default arguments: a copy or move constructor with a
6584 // default argument is classified as a default constructor, and assignment
6585 // operations and destructors can't have default arguments.
6586 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6587 << CSM << MD->getSourceRange();
6588 HadError = true;
6589 } else if (MD->isVariadic()) {
6590 if (DeleteOnTypeMismatch)
6591 ShouldDeleteForTypeMismatch = true;
6592 else {
6593 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6594 << CSM << MD->getSourceRange();
6595 HadError = true;
6596 }
6597 }
6598
6599 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6600
6601 bool CanHaveConstParam = false;
6602 if (CSM == CXXCopyConstructor)
6603 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6604 else if (CSM == CXXCopyAssignment)
6605 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6606
6607 QualType ReturnType = Context.VoidTy;
6608 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6609 // Check for return type matching.
6610 ReturnType = Type->getReturnType();
6611
6612 QualType DeclType = Context.getTypeDeclType(RD);
6613 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6614 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6615
6616 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6617 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6618 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6619 HadError = true;
6620 }
6621
6622 // A defaulted special member cannot have cv-qualifiers.
6623 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6624 if (DeleteOnTypeMismatch)
6625 ShouldDeleteForTypeMismatch = true;
6626 else {
6627 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6628 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6629 HadError = true;
6630 }
6631 }
6632 }
6633
6634 // Check for parameter type matching.
6635 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6636 bool HasConstParam = false;
6637 if (ExpectedParams && ArgType->isReferenceType()) {
6638 // Argument must be reference to possibly-const T.
6639 QualType ReferentType = ArgType->getPointeeType();
6640 HasConstParam = ReferentType.isConstQualified();
6641
6642 if (ReferentType.isVolatileQualified()) {
6643 if (DeleteOnTypeMismatch)
6644 ShouldDeleteForTypeMismatch = true;
6645 else {
6646 Diag(MD->getLocation(),
6647 diag::err_defaulted_special_member_volatile_param) << CSM;
6648 HadError = true;
6649 }
6650 }
6651
6652 if (HasConstParam && !CanHaveConstParam) {
6653 if (DeleteOnTypeMismatch)
6654 ShouldDeleteForTypeMismatch = true;
6655 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6656 Diag(MD->getLocation(),
6657 diag::err_defaulted_special_member_copy_const_param)
6658 << (CSM == CXXCopyAssignment);
6659 // FIXME: Explain why this special member can't be const.
6660 HadError = true;
6661 } else {
6662 Diag(MD->getLocation(),
6663 diag::err_defaulted_special_member_move_const_param)
6664 << (CSM == CXXMoveAssignment);
6665 HadError = true;
6666 }
6667 }
6668 } else if (ExpectedParams) {
6669 // A copy assignment operator can take its argument by value, but a
6670 // defaulted one cannot.
6671 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6672 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6673 HadError = true;
6674 }
6675
6676 // C++11 [dcl.fct.def.default]p2:
6677 // An explicitly-defaulted function may be declared constexpr only if it
6678 // would have been implicitly declared as constexpr,
6679 // Do not apply this rule to members of class templates, since core issue 1358
6680 // makes such functions always instantiate to constexpr functions. For
6681 // functions which cannot be constexpr (for non-constructors in C++11 and for
6682 // destructors in C++1y), this is checked elsewhere.
6683 //
6684 // FIXME: This should not apply if the member is deleted.
6685 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6686 HasConstParam);
6687 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6688 : isa<CXXConstructorDecl>(MD)) &&
6689 MD->isConstexpr() && !Constexpr &&
6690 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6691 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM;
6692 // FIXME: Explain why the special member can't be constexpr.
6693 HadError = true;
6694 }
6695
6696 if (First) {
6697 // C++2a [dcl.fct.def.default]p3:
6698 // If a function is explicitly defaulted on its first declaration, it is
6699 // implicitly considered to be constexpr if the implicit declaration
6700 // would be.
6701 MD->setConstexpr(Constexpr);
6702
6703 if (!Type->hasExceptionSpec()) {
6704 // C++2a [except.spec]p3:
6705 // If a declaration of a function does not have a noexcept-specifier
6706 // [and] is defaulted on its first declaration, [...] the exception
6707 // specification is as specified below
6708 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6709 EPI.ExceptionSpec.Type = EST_Unevaluated;
6710 EPI.ExceptionSpec.SourceDecl = MD;
6711 MD->setType(Context.getFunctionType(ReturnType,
6712 llvm::makeArrayRef(&ArgType,
6713 ExpectedParams),
6714 EPI));
6715 }
6716 }
6717
6718 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6719 if (First) {
6720 SetDeclDeleted(MD, MD->getLocation());
6721 if (!inTemplateInstantiation() && !HadError) {
6722 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6723 if (ShouldDeleteForTypeMismatch) {
6724 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6725 } else {
6726 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6727 }
6728 }
6729 if (ShouldDeleteForTypeMismatch && !HadError) {
6730 Diag(MD->getLocation(),
6731 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6732 }
6733 } else {
6734 // C++11 [dcl.fct.def.default]p4:
6735 // [For a] user-provided explicitly-defaulted function [...] if such a
6736 // function is implicitly defined as deleted, the program is ill-formed.
6737 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6738 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6739 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6740 HadError = true;
6741 }
6742 }
6743
6744 if (HadError)
6745 MD->setInvalidDecl();
6746}
6747
6748void Sema::CheckDelayedMemberExceptionSpecs() {
6749 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6750 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6751
6752 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6753 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6754
6755 // Perform any deferred checking of exception specifications for virtual
6756 // destructors.
6757 for (auto &Check : Overriding)
6758 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6759
6760 // Perform any deferred checking of exception specifications for befriended
6761 // special members.
6762 for (auto &Check : Equivalent)
6763 CheckEquivalentExceptionSpec(Check.second, Check.first);
6764}
6765
6766namespace {
6767/// CRTP base class for visiting operations performed by a special member
6768/// function (or inherited constructor).
6769template<typename Derived>
6770struct SpecialMemberVisitor {
6771 Sema &S;
6772 CXXMethodDecl *MD;
6773 Sema::CXXSpecialMember CSM;
6774 Sema::InheritedConstructorInfo *ICI;
6775
6776 // Properties of the special member, computed for convenience.
6777 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6778
6779 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6780 Sema::InheritedConstructorInfo *ICI)
6781 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6782 switch (CSM) {
6783 case Sema::CXXDefaultConstructor:
6784 case Sema::CXXCopyConstructor:
6785 case Sema::CXXMoveConstructor:
6786 IsConstructor = true;
6787 break;
6788 case Sema::CXXCopyAssignment:
6789 case Sema::CXXMoveAssignment:
6790 IsAssignment = true;
6791 break;
6792 case Sema::CXXDestructor:
6793 break;
6794 case Sema::CXXInvalid:
6795 llvm_unreachable("invalid special member kind");
6796 }
6797
6798 if (MD->getNumParams()) {
6799 if (const ReferenceType *RT =
6800 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6801 ConstArg = RT->getPointeeType().isConstQualified();
6802 }
6803 }
6804
6805 Derived &getDerived() { return static_cast<Derived&>(*this); }
6806
6807 /// Is this a "move" special member?
6808 bool isMove() const {
6809 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6810 }
6811
6812 /// Look up the corresponding special member in the given class.
6813 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6814 unsigned Quals, bool IsMutable) {
6815 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6816 ConstArg && !IsMutable);
6817 }
6818
6819 /// Look up the constructor for the specified base class to see if it's
6820 /// overridden due to this being an inherited constructor.
6821 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6822 if (!ICI)
6823 return {};
6824 assert(CSM == Sema::CXXDefaultConstructor);
6825 auto *BaseCtor =
6826 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6827 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6828 return MD;
6829 return {};
6830 }
6831
6832 /// A base or member subobject.
6833 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6834
6835 /// Get the location to use for a subobject in diagnostics.
6836 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6837 // FIXME: For an indirect virtual base, the direct base leading to
6838 // the indirect virtual base would be a more useful choice.
6839 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6840 return B->getBaseTypeLoc();
6841 else
6842 return Subobj.get<FieldDecl*>()->getLocation();
6843 }
6844
6845 enum BasesToVisit {
6846 /// Visit all non-virtual (direct) bases.
6847 VisitNonVirtualBases,
6848 /// Visit all direct bases, virtual or not.
6849 VisitDirectBases,
6850 /// Visit all non-virtual bases, and all virtual bases if the class
6851 /// is not abstract.
6852 VisitPotentiallyConstructedBases,
6853 /// Visit all direct or virtual bases.
6854 VisitAllBases
6855 };
6856
6857 // Visit the bases and members of the class.
6858 bool visit(BasesToVisit Bases) {
6859 CXXRecordDecl *RD = MD->getParent();
6860
6861 if (Bases == VisitPotentiallyConstructedBases)
6862 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6863
6864 for (auto &B : RD->bases())
6865 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6866 getDerived().visitBase(&B))
6867 return true;
6868
6869 if (Bases == VisitAllBases)
6870 for (auto &B : RD->vbases())
6871 if (getDerived().visitBase(&B))
6872 return true;
6873
6874 for (auto *F : RD->fields())
6875 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6876 getDerived().visitField(F))
6877 return true;
6878
6879 return false;
6880 }
6881};
6882}
6883
6884namespace {
6885struct SpecialMemberDeletionInfo
6886 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6887 bool Diagnose;
6888
6889 SourceLocation Loc;
6890
6891 bool AllFieldsAreConst;
6892
6893 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6894 Sema::CXXSpecialMember CSM,
6895 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6896 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6897 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6898
6899 bool inUnion() const { return MD->getParent()->isUnion(); }
6900
6901 Sema::CXXSpecialMember getEffectiveCSM() {
6902 return ICI ? Sema::CXXInvalid : CSM;
6903 }
6904
6905 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6906
6907 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6908 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6909
6910 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6911 bool shouldDeleteForField(FieldDecl *FD);
6912 bool shouldDeleteForAllConstMembers();
6913
6914 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6915 unsigned Quals);
6916 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6917 Sema::SpecialMemberOverloadResult SMOR,
6918 bool IsDtorCallInCtor);
6919
6920 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6921};
6922}
6923
6924/// Is the given special member inaccessible when used on the given
6925/// sub-object.
6926bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6927 CXXMethodDecl *target) {
6928 /// If we're operating on a base class, the object type is the
6929 /// type of this special member.
6930 QualType objectTy;
6931 AccessSpecifier access = target->getAccess();
6932 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6933 objectTy = S.Context.getTypeDeclType(MD->getParent());
6934 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6935
6936 // If we're operating on a field, the object type is the type of the field.
6937 } else {
6938 objectTy = S.Context.getTypeDeclType(target->getParent());
6939 }
6940
6941 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6942}
6943
6944/// Check whether we should delete a special member due to the implicit
6945/// definition containing a call to a special member of a subobject.
6946bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6947 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6948 bool IsDtorCallInCtor) {
6949 CXXMethodDecl *Decl = SMOR.getMethod();
6950 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6951
6952 int DiagKind = -1;
6953
6954 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6955 DiagKind = !Decl ? 0 : 1;
6956 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6957 DiagKind = 2;
6958 else if (!isAccessible(Subobj, Decl))
6959 DiagKind = 3;
6960 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6961 !Decl->isTrivial()) {
6962 // A member of a union must have a trivial corresponding special member.
6963 // As a weird special case, a destructor call from a union's constructor
6964 // must be accessible and non-deleted, but need not be trivial. Such a
6965 // destructor is never actually called, but is semantically checked as
6966 // if it were.
6967 DiagKind = 4;
6968 }
6969
6970 if (DiagKind == -1)
6971 return false;
6972
6973 if (Diagnose) {
6974 if (Field) {
6975 S.Diag(Field->getLocation(),
6976 diag::note_deleted_special_member_class_subobject)
6977 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6978 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6979 } else {
6980 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6981 S.Diag(Base->getBeginLoc(),
6982 diag::note_deleted_special_member_class_subobject)
6983 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6984 << Base->getType() << DiagKind << IsDtorCallInCtor
6985 << /*IsObjCPtr*/false;
6986 }
6987
6988 if (DiagKind == 1)
6989 S.NoteDeletedFunction(Decl);
6990 // FIXME: Explain inaccessibility if DiagKind == 3.
6991 }
6992
6993 return true;
6994}
6995
6996/// Check whether we should delete a special member function due to having a
6997/// direct or virtual base class or non-static data member of class type M.
6998bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6999 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7000 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7001 bool IsMutable = Field && Field->isMutable();
7002
7003 // C++11 [class.ctor]p5:
7004 // -- any direct or virtual base class, or non-static data member with no
7005 // brace-or-equal-initializer, has class type M (or array thereof) and
7006 // either M has no default constructor or overload resolution as applied
7007 // to M's default constructor results in an ambiguity or in a function
7008 // that is deleted or inaccessible
7009 // C++11 [class.copy]p11, C++11 [class.copy]p23:
7010 // -- a direct or virtual base class B that cannot be copied/moved because
7011 // overload resolution, as applied to B's corresponding special member,
7012 // results in an ambiguity or a function that is deleted or inaccessible
7013 // from the defaulted special member
7014 // C++11 [class.dtor]p5:
7015 // -- any direct or virtual base class [...] has a type with a destructor
7016 // that is deleted or inaccessible
7017 if (!(CSM == Sema::CXXDefaultConstructor &&
7018 Field && Field->hasInClassInitializer()) &&
7019 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7020 false))
7021 return true;
7022
7023 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7024 // -- any direct or virtual base class or non-static data member has a
7025 // type with a destructor that is deleted or inaccessible
7026 if (IsConstructor) {
7027 Sema::SpecialMemberOverloadResult SMOR =
7028 S.LookupSpecialMember(Class, Sema::CXXDestructor,
7029 false, false, false, false, false);
7030 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7031 return true;
7032 }
7033
7034 return false;
7035}
7036
7037bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7038 FieldDecl *FD, QualType FieldType) {
7039 // The defaulted special functions are defined as deleted if this is a variant
7040 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7041 // type under ARC.
7042 if (!FieldType.hasNonTrivialObjCLifetime())
7043 return false;
7044
7045 // Don't make the defaulted default constructor defined as deleted if the
7046 // member has an in-class initializer.
7047 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7048 return false;
7049
7050 if (Diagnose) {
7051 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7052 S.Diag(FD->getLocation(),
7053 diag::note_deleted_special_member_class_subobject)
7054 << getEffectiveCSM() << ParentClass << /*IsField*/true
7055 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7056 }
7057
7058 return true;
7059}
7060
7061/// Check whether we should delete a special member function due to the class
7062/// having a particular direct or virtual base class.
7063bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7064 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7065 // If program is correct, BaseClass cannot be null, but if it is, the error
7066 // must be reported elsewhere.
7067 if (!BaseClass)
7068 return false;
7069 // If we have an inheriting constructor, check whether we're calling an
7070 // inherited constructor instead of a default constructor.
7071 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7072 if (auto *BaseCtor = SMOR.getMethod()) {
7073 // Note that we do not check access along this path; other than that,
7074 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7075 // FIXME: Check that the base has a usable destructor! Sink this into
7076 // shouldDeleteForClassSubobject.
7077 if (BaseCtor->isDeleted() && Diagnose) {
7078 S.Diag(Base->getBeginLoc(),
7079 diag::note_deleted_special_member_class_subobject)
7080 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7081 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7082 << /*IsObjCPtr*/false;
7083 S.NoteDeletedFunction(BaseCtor);
7084 }
7085 return BaseCtor->isDeleted();
7086 }
7087 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7088}
7089
7090/// Check whether we should delete a special member function due to the class
7091/// having a particular non-static data member.
7092bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7093 QualType FieldType = S.Context.getBaseElementType(FD->getType());
7094 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7095
7096 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7097 return true;
7098
7099 if (CSM == Sema::CXXDefaultConstructor) {
7100 // For a default constructor, all references must be initialized in-class
7101 // and, if a union, it must have a non-const member.
7102 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7103 if (Diagnose)
7104 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7105 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7106 return true;
7107 }
7108 // C++11 [class.ctor]p5: any non-variant non-static data member of
7109 // const-qualified type (or array thereof) with no
7110 // brace-or-equal-initializer does not have a user-provided default
7111 // constructor.
7112 if (!inUnion() && FieldType.isConstQualified() &&
7113 !FD->hasInClassInitializer() &&
7114 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7115 if (Diagnose)
7116 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7117 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7118 return true;
7119 }
7120
7121 if (inUnion() && !FieldType.isConstQualified())
7122 AllFieldsAreConst = false;
7123 } else if (CSM == Sema::CXXCopyConstructor) {
7124 // For a copy constructor, data members must not be of rvalue reference
7125 // type.
7126 if (FieldType->isRValueReferenceType()) {
7127 if (Diagnose)
7128 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7129 << MD->getParent() << FD << FieldType;
7130 return true;
7131 }
7132 } else if (IsAssignment) {
7133 // For an assignment operator, data members must not be of reference type.
7134 if (FieldType->isReferenceType()) {
7135 if (Diagnose)
7136 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7137 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7138 return true;
7139 }
7140 if (!FieldRecord && FieldType.isConstQualified()) {
7141 // C++11 [class.copy]p23:
7142 // -- a non-static data member of const non-class type (or array thereof)
7143 if (Diagnose)
7144 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7145 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7146 return true;
7147 }
7148 }
7149
7150 if (FieldRecord) {
7151 // Some additional restrictions exist on the variant members.
7152 if (!inUnion() && FieldRecord->isUnion() &&
7153 FieldRecord->isAnonymousStructOrUnion()) {
7154 bool AllVariantFieldsAreConst = true;
7155
7156 // FIXME: Handle anonymous unions declared within anonymous unions.
7157 for (auto *UI : FieldRecord->fields()) {
7158 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7159
7160 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7161 return true;
7162
7163 if (!UnionFieldType.isConstQualified())
7164 AllVariantFieldsAreConst = false;
7165
7166 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7167 if (UnionFieldRecord &&
7168 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7169 UnionFieldType.getCVRQualifiers()))
7170 return true;
7171 }
7172
7173 // At least one member in each anonymous union must be non-const
7174 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7175 !FieldRecord->field_empty()) {
7176 if (Diagnose)
7177 S.Diag(FieldRecord->getLocation(),
7178 diag::note_deleted_default_ctor_all_const)
7179 << !!ICI << MD->getParent() << /*anonymous union*/1;
7180 return true;
7181 }
7182
7183 // Don't check the implicit member of the anonymous union type.
7184 // This is technically non-conformant, but sanity demands it.
7185 return false;
7186 }
7187
7188 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7189 FieldType.getCVRQualifiers()))
7190 return true;
7191 }
7192
7193 return false;
7194}
7195
7196/// C++11 [class.ctor] p5:
7197/// A defaulted default constructor for a class X is defined as deleted if
7198/// X is a union and all of its variant members are of const-qualified type.
7199bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7200 // This is a silly definition, because it gives an empty union a deleted
7201 // default constructor. Don't do that.
7202 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7203 bool AnyFields = false;
7204 for (auto *F : MD->getParent()->fields())
7205 if ((AnyFields = !F->isUnnamedBitfield()))
7206 break;
7207 if (!AnyFields)
7208 return false;
7209 if (Diagnose)
7210 S.Diag(MD->getParent()->getLocation(),
7211 diag::note_deleted_default_ctor_all_const)
7212 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7213 return true;
7214 }
7215 return false;
7216}
7217
7218/// Determine whether a defaulted special member function should be defined as
7219/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7220/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7221bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7222 InheritedConstructorInfo *ICI,
7223 bool Diagnose) {
7224 if (MD->isInvalidDecl())
7225 return false;
7226 CXXRecordDecl *RD = MD->getParent();
7227 assert(!RD->isDependentType() && "do deletion after instantiation");
7228 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7229 return false;
7230
7231 // C++11 [expr.lambda.prim]p19:
7232 // The closure type associated with a lambda-expression has a
7233 // deleted (8.4.3) default constructor and a deleted copy
7234 // assignment operator.
7235 // C++2a adds back these operators if the lambda has no capture-default.
7236 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7237 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7238 if (Diagnose)
7239 Diag(RD->getLocation(), diag::note_lambda_decl);
7240 return true;
7241 }
7242
7243 // For an anonymous struct or union, the copy and assignment special members
7244 // will never be used, so skip the check. For an anonymous union declared at
7245 // namespace scope, the constructor and destructor are used.
7246 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7247 RD->isAnonymousStructOrUnion())
7248 return false;
7249
7250 // C++11 [class.copy]p7, p18:
7251 // If the class definition declares a move constructor or move assignment
7252 // operator, an implicitly declared copy constructor or copy assignment
7253 // operator is defined as deleted.
7254 if (MD->isImplicit() &&
7255 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7256 CXXMethodDecl *UserDeclaredMove = nullptr;
7257
7258 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7259 // deletion of the corresponding copy operation, not both copy operations.
7260 // MSVC 2015 has adopted the standards conforming behavior.
7261 bool DeletesOnlyMatchingCopy =
7262 getLangOpts().MSVCCompat &&
7263 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7264
7265 if (RD->hasUserDeclaredMoveConstructor() &&
7266 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7267 if (!Diagnose) return true;
7268
7269 // Find any user-declared move constructor.
7270 for (auto *I : RD->ctors()) {
7271 if (I->isMoveConstructor()) {
7272 UserDeclaredMove = I;
7273 break;
7274 }
7275 }
7276 assert(UserDeclaredMove);
7277 } else if (RD->hasUserDeclaredMoveAssignment() &&
7278 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7279 if (!Diagnose) return true;
7280
7281 // Find any user-declared move assignment operator.
7282 for (auto *I : RD->methods()) {
7283 if (I->isMoveAssignmentOperator()) {
7284 UserDeclaredMove = I;
7285 break;
7286 }
7287 }
7288 assert(UserDeclaredMove);
7289 }
7290
7291 if (UserDeclaredMove) {
7292 Diag(UserDeclaredMove->getLocation(),
7293 diag::note_deleted_copy_user_declared_move)
7294 << (CSM == CXXCopyAssignment) << RD
7295 << UserDeclaredMove->isMoveAssignmentOperator();
7296 return true;
7297 }
7298 }
7299
7300 // Do access control from the special member function
7301 ContextRAII MethodContext(*this, MD);
7302
7303 // C++11 [class.dtor]p5:
7304 // -- for a virtual destructor, lookup of the non-array deallocation function
7305 // results in an ambiguity or in a function that is deleted or inaccessible
7306 if (CSM == CXXDestructor && MD->isVirtual()) {
7307 FunctionDecl *OperatorDelete = nullptr;
7308 DeclarationName Name =
7309 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7310 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7311 OperatorDelete, /*Diagnose*/false)) {
7312 if (Diagnose)
7313 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7314 return true;
7315 }
7316 }
7317
7318 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7319
7320 // Per DR1611, do not consider virtual bases of constructors of abstract
7321 // classes, since we are not going to construct them.
7322 // Per DR1658, do not consider virtual bases of destructors of abstract
7323 // classes either.
7324 // Per DR2180, for assignment operators we only assign (and thus only
7325 // consider) direct bases.
7326 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7327 : SMI.VisitPotentiallyConstructedBases))
7328 return true;
7329
7330 if (SMI.shouldDeleteForAllConstMembers())
7331 return true;
7332
7333 if (getLangOpts().CUDA) {
7334 // We should delete the special member in CUDA mode if target inference
7335 // failed.
7336 // For inherited constructors (non-null ICI), CSM may be passed so that MD
7337 // is treated as certain special member, which may not reflect what special
7338 // member MD really is. However inferCUDATargetForImplicitSpecialMember
7339 // expects CSM to match MD, therefore recalculate CSM.
7340 assert(ICI || CSM == getSpecialMember(MD));
7341 auto RealCSM = CSM;
7342 if (ICI)
7343 RealCSM = getSpecialMember(MD);
7344
7345 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7346 SMI.ConstArg, Diagnose);
7347 }
7348
7349 return false;
7350}
7351
7352/// Perform lookup for a special member of the specified kind, and determine
7353/// whether it is trivial. If the triviality can be determined without the
7354/// lookup, skip it. This is intended for use when determining whether a
7355/// special member of a containing object is trivial, and thus does not ever
7356/// perform overload resolution for default constructors.
7357///
7358/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7359/// member that was most likely to be intended to be trivial, if any.
7360///
7361/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7362/// determine whether the special member is trivial.
7363static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7364 Sema::CXXSpecialMember CSM, unsigned Quals,
7365 bool ConstRHS,
7366 Sema::TrivialABIHandling TAH,
7367 CXXMethodDecl **Selected) {
7368 if (Selected)
7369 *Selected = nullptr;
7370
7371 switch (CSM) {
7372 case Sema::CXXInvalid:
7373 llvm_unreachable("not a special member");
7374
7375 case Sema::CXXDefaultConstructor:
7376 // C++11 [class.ctor]p5:
7377 // A default constructor is trivial if:
7378 // - all the [direct subobjects] have trivial default constructors
7379 //
7380 // Note, no overload resolution is performed in this case.
7381 if (RD->hasTrivialDefaultConstructor())
7382 return true;
7383
7384 if (Selected) {
7385 // If there's a default constructor which could have been trivial, dig it
7386 // out. Otherwise, if there's any user-provided default constructor, point
7387 // to that as an example of why there's not a trivial one.
7388 CXXConstructorDecl *DefCtor = nullptr;
7389 if (RD->needsImplicitDefaultConstructor())
7390 S.DeclareImplicitDefaultConstructor(RD);
7391 for (auto *CI : RD->ctors()) {
7392 if (!CI->isDefaultConstructor())
7393 continue;
7394 DefCtor = CI;
7395 if (!DefCtor->isUserProvided())
7396 break;
7397 }
7398
7399 *Selected = DefCtor;
7400 }
7401
7402 return false;
7403
7404 case Sema::CXXDestructor:
7405 // C++11 [class.dtor]p5:
7406 // A destructor is trivial if:
7407 // - all the direct [subobjects] have trivial destructors
7408 if (RD->hasTrivialDestructor() ||
7409 (TAH == Sema::TAH_ConsiderTrivialABI &&
7410 RD->hasTrivialDestructorForCall()))
7411 return true;
7412
7413 if (Selected) {
7414 if (RD->needsImplicitDestructor())
7415 S.DeclareImplicitDestructor(RD);
7416 *Selected = RD->getDestructor();
7417 }
7418
7419 return false;
7420
7421 case Sema::CXXCopyConstructor:
7422 // C++11 [class.copy]p12:
7423 // A copy constructor is trivial if:
7424 // - the constructor selected to copy each direct [subobject] is trivial
7425 if (RD->hasTrivialCopyConstructor() ||
7426 (TAH == Sema::TAH_ConsiderTrivialABI &&
7427 RD->hasTrivialCopyConstructorForCall())) {
7428 if (Quals == Qualifiers::Const)
7429 // We must either select the trivial copy constructor or reach an
7430 // ambiguity; no need to actually perform overload resolution.
7431 return true;
7432 } else if (!Selected) {
7433 return false;
7434 }
7435 // In C++98, we are not supposed to perform overload resolution here, but we
7436 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7437 // cases like B as having a non-trivial copy constructor:
7438 // struct A { template<typename T> A(T&); };
7439 // struct B { mutable A a; };
7440 goto NeedOverloadResolution;
7441
7442 case Sema::CXXCopyAssignment:
7443 // C++11 [class.copy]p25:
7444 // A copy assignment operator is trivial if:
7445 // - the assignment operator selected to copy each direct [subobject] is
7446 // trivial
7447 if (RD->hasTrivialCopyAssignment()) {
7448 if (Quals == Qualifiers::Const)
7449 return true;
7450 } else if (!Selected) {
7451 return false;
7452 }
7453 // In C++98, we are not supposed to perform overload resolution here, but we
7454 // treat that as a language defect.
7455 goto NeedOverloadResolution;
7456
7457 case Sema::CXXMoveConstructor:
7458 case Sema::CXXMoveAssignment:
7459 NeedOverloadResolution:
7460 Sema::SpecialMemberOverloadResult SMOR =
7461 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7462
7463 // The standard doesn't describe how to behave if the lookup is ambiguous.
7464 // We treat it as not making the member non-trivial, just like the standard
7465 // mandates for the default constructor. This should rarely matter, because
7466 // the member will also be deleted.
7467 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7468 return true;
7469
7470 if (!SMOR.getMethod()) {
7471 assert(SMOR.getKind() ==
7472 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7473 return false;
7474 }
7475
7476 // We deliberately don't check if we found a deleted special member. We're
7477 // not supposed to!
7478 if (Selected)
7479 *Selected = SMOR.getMethod();
7480
7481 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7482 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7483 return SMOR.getMethod()->isTrivialForCall();
7484 return SMOR.getMethod()->isTrivial();
7485 }
7486
7487 llvm_unreachable("unknown special method kind");
7488}
7489
7490static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7491 for (auto *CI : RD->ctors())
7492 if (!CI->isImplicit())
7493 return CI;
7494
7495 // Look for constructor templates.
7496 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7497 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7498 if (CXXConstructorDecl *CD =
7499 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7500 return CD;
7501 }
7502
7503 return nullptr;
7504}
7505
7506/// The kind of subobject we are checking for triviality. The values of this
7507/// enumeration are used in diagnostics.
7508enum TrivialSubobjectKind {
7509 /// The subobject is a base class.
7510 TSK_BaseClass,
7511 /// The subobject is a non-static data member.
7512 TSK_Field,
7513 /// The object is actually the complete object.
7514 TSK_CompleteObject
7515};
7516
7517/// Check whether the special member selected for a given type would be trivial.
7518static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7519 QualType SubType, bool ConstRHS,
7520 Sema::CXXSpecialMember CSM,
7521 TrivialSubobjectKind Kind,
7522 Sema::TrivialABIHandling TAH, bool Diagnose) {
7523 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7524 if (!SubRD)
7525 return true;
7526
7527 CXXMethodDecl *Selected;
7528 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7529 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7530 return true;
7531
7532 if (Diagnose) {
7533 if (ConstRHS)
7534 SubType.addConst();
7535
7536 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7537 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7538 << Kind << SubType.getUnqualifiedType();
7539 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7540 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7541 } else if (!Selected)
7542 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7543 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7544 else if (Selected->isUserProvided()) {
7545 if (Kind == TSK_CompleteObject)
7546 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7547 << Kind << SubType.getUnqualifiedType() << CSM;
7548 else {
7549 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7550 << Kind << SubType.getUnqualifiedType() << CSM;
7551 S.Diag(Selected->getLocation(), diag::note_declared_at);
7552 }
7553 } else {
7554 if (Kind != TSK_CompleteObject)
7555 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7556 << Kind << SubType.getUnqualifiedType() << CSM;
7557
7558 // Explain why the defaulted or deleted special member isn't trivial.
7559 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7560 Diagnose);
7561 }
7562 }
7563
7564 return false;
7565}
7566
7567/// Check whether the members of a class type allow a special member to be
7568/// trivial.
7569static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7570 Sema::CXXSpecialMember CSM,
7571 bool ConstArg,
7572 Sema::TrivialABIHandling TAH,
7573 bool Diagnose) {
7574 for (const auto *FI : RD->fields()) {
7575 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7576 continue;
7577
7578 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7579
7580 // Pretend anonymous struct or union members are members of this class.
7581 if (FI->isAnonymousStructOrUnion()) {
7582 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7583 CSM, ConstArg, TAH, Diagnose))
7584 return false;
7585 continue;
7586 }
7587
7588 // C++11 [class.ctor]p5:
7589 // A default constructor is trivial if [...]
7590 // -- no non-static data member of its class has a
7591 // brace-or-equal-initializer
7592 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7593 if (Diagnose)
7594 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7595 return false;
7596 }
7597
7598 // Objective C ARC 4.3.5:
7599 // [...] nontrivally ownership-qualified types are [...] not trivially
7600 // default constructible, copy constructible, move constructible, copy
7601 // assignable, move assignable, or destructible [...]
7602 if (FieldType.hasNonTrivialObjCLifetime()) {
7603 if (Diagnose)
7604 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7605 << RD << FieldType.getObjCLifetime();
7606 return false;
7607 }
7608
7609 bool ConstRHS = ConstArg && !FI->isMutable();
7610 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7611 CSM, TSK_Field, TAH, Diagnose))
7612 return false;
7613 }
7614
7615 return true;
7616}
7617
7618/// Diagnose why the specified class does not have a trivial special member of
7619/// the given kind.
7620void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7621 QualType Ty = Context.getRecordType(RD);
7622
7623 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7624 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7625 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7626 /*Diagnose*/true);
7627}
7628
7629/// Determine whether a defaulted or deleted special member function is trivial,
7630/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7631/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7632bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7633 TrivialABIHandling TAH, bool Diagnose) {
7634 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7635
7636 CXXRecordDecl *RD = MD->getParent();
7637
7638 bool ConstArg = false;
7639
7640 // C++11 [class.copy]p12, p25: [DR1593]
7641 // A [special member] is trivial if [...] its parameter-type-list is
7642 // equivalent to the parameter-type-list of an implicit declaration [...]
7643 switch (CSM) {
7644 case CXXDefaultConstructor:
7645 case CXXDestructor:
7646 // Trivial default constructors and destructors cannot have parameters.
7647 break;
7648
7649 case CXXCopyConstructor:
7650 case CXXCopyAssignment: {
7651 // Trivial copy operations always have const, non-volatile parameter types.
7652 ConstArg = true;
7653 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7654 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7655 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7656 if (Diagnose)
7657 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7658 << Param0->getSourceRange() << Param0->getType()
7659 << Context.getLValueReferenceType(
7660 Context.getRecordType(RD).withConst());
7661 return false;
7662 }
7663 break;
7664 }
7665
7666 case CXXMoveConstructor:
7667 case CXXMoveAssignment: {
7668 // Trivial move operations always have non-cv-qualified parameters.
7669 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7670 const RValueReferenceType *RT =
7671 Param0->getType()->getAs<RValueReferenceType>();
7672 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7673 if (Diagnose)
7674 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7675 << Param0->getSourceRange() << Param0->getType()
7676 << Context.getRValueReferenceType(Context.getRecordType(RD));
7677 return false;
7678 }
7679 break;
7680 }
7681
7682 case CXXInvalid:
7683 llvm_unreachable("not a special member");
7684 }
7685
7686 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7687 if (Diagnose)
7688 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7689 diag::note_nontrivial_default_arg)
7690 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7691 return false;
7692 }
7693 if (MD->isVariadic()) {
7694 if (Diagnose)
7695 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7696 return false;
7697 }
7698
7699 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7700 // A copy/move [constructor or assignment operator] is trivial if
7701 // -- the [member] selected to copy/move each direct base class subobject
7702 // is trivial
7703 //
7704 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7705 // A [default constructor or destructor] is trivial if
7706 // -- all the direct base classes have trivial [default constructors or
7707 // destructors]
7708 for (const auto &BI : RD->bases())
7709 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7710 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7711 return false;
7712
7713 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7714 // A copy/move [constructor or assignment operator] for a class X is
7715 // trivial if
7716 // -- for each non-static data member of X that is of class type (or array
7717 // thereof), the constructor selected to copy/move that member is
7718 // trivial
7719 //
7720 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7721 // A [default constructor or destructor] is trivial if
7722 // -- for all of the non-static data members of its class that are of class
7723 // type (or array thereof), each such class has a trivial [default
7724 // constructor or destructor]
7725 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7726 return false;
7727
7728 // C++11 [class.dtor]p5:
7729 // A destructor is trivial if [...]
7730 // -- the destructor is not virtual
7731 if (CSM == CXXDestructor && MD->isVirtual()) {
7732 if (Diagnose)
7733 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7734 return false;
7735 }
7736
7737 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7738 // A [special member] for class X is trivial if [...]
7739 // -- class X has no virtual functions and no virtual base classes
7740 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7741 if (!Diagnose)
7742 return false;
7743
7744 if (RD->getNumVBases()) {
7745 // Check for virtual bases. We already know that the corresponding
7746 // member in all bases is trivial, so vbases must all be direct.
7747 CXXBaseSpecifier &BS = *RD->vbases_begin();
7748 assert(BS.isVirtual());
7749 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7750 return false;
7751 }
7752
7753 // Must have a virtual method.
7754 for (const auto *MI : RD->methods()) {
7755 if (MI->isVirtual()) {
7756 SourceLocation MLoc = MI->getBeginLoc();
7757 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7758 return false;
7759 }
7760 }
7761
7762 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7763 }
7764
7765 // Looks like it's trivial!
7766 return true;
7767}
7768
7769namespace {
7770struct FindHiddenVirtualMethod {
7771 Sema *S;
7772 CXXMethodDecl *Method;
7773 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7774 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7775
7776private:
7777 /// Check whether any most overridden method from MD in Methods
7778 static bool CheckMostOverridenMethods(
7779 const CXXMethodDecl *MD,
7780 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7781 if (MD->size_overridden_methods() == 0)
7782 return Methods.count(MD->getCanonicalDecl());
7783 for (const CXXMethodDecl *O : MD->overridden_methods())
7784 if (CheckMostOverridenMethods(O, Methods))
7785 return true;
7786 return false;
7787 }
7788
7789public:
7790 /// Member lookup function that determines whether a given C++
7791 /// method overloads virtual methods in a base class without overriding any,
7792 /// to be used with CXXRecordDecl::lookupInBases().
7793 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7794 RecordDecl *BaseRecord =
7795 Specifier->getType()->getAs<RecordType>()->getDecl();
7796
7797 DeclarationName Name = Method->getDeclName();
7798 assert(Name.getNameKind() == DeclarationName::Identifier);
7799
7800 bool foundSameNameMethod = false;
7801 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7802 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7803 Path.Decls = Path.Decls.slice(1)) {
7804 NamedDecl *D = Path.Decls.front();
7805 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7806 MD = MD->getCanonicalDecl();
7807 foundSameNameMethod = true;
7808 // Interested only in hidden virtual methods.
7809 if (!MD->isVirtual())
7810 continue;
7811 // If the method we are checking overrides a method from its base
7812 // don't warn about the other overloaded methods. Clang deviates from
7813 // GCC by only diagnosing overloads of inherited virtual functions that
7814 // do not override any other virtual functions in the base. GCC's
7815 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7816 // function from a base class. These cases may be better served by a
7817 // warning (not specific to virtual functions) on call sites when the
7818 // call would select a different function from the base class, were it
7819 // visible.
7820 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7821 if (!S->IsOverload(Method, MD, false))
7822 return true;
7823 // Collect the overload only if its hidden.
7824 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7825 overloadedMethods.push_back(MD);
7826 }
7827 }
7828
7829 if (foundSameNameMethod)
7830 OverloadedMethods.append(overloadedMethods.begin(),
7831 overloadedMethods.end());
7832 return foundSameNameMethod;
7833 }
7834};
7835} // end anonymous namespace
7836
7837/// Add the most overriden methods from MD to Methods
7838static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7839 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7840 if (MD->size_overridden_methods() == 0)
7841 Methods.insert(MD->getCanonicalDecl());
7842 else
7843 for (const CXXMethodDecl *O : MD->overridden_methods())
7844 AddMostOverridenMethods(O, Methods);
7845}
7846
7847/// Check if a method overloads virtual methods in a base class without
7848/// overriding any.
7849void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7850 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7851 if (!MD->getDeclName().isIdentifier())
7852 return;
7853
7854 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7855 /*bool RecordPaths=*/false,
7856 /*bool DetectVirtual=*/false);
7857 FindHiddenVirtualMethod FHVM;
7858 FHVM.Method = MD;
7859 FHVM.S = this;
7860
7861 // Keep the base methods that were overridden or introduced in the subclass
7862 // by 'using' in a set. A base method not in this set is hidden.
7863 CXXRecordDecl *DC = MD->getParent();
7864 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7865 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7866 NamedDecl *ND = *I;
7867 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7868 ND = shad->getTargetDecl();
7869 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7870 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7871 }
7872
7873 if (DC->lookupInBases(FHVM, Paths))
7874 OverloadedMethods = FHVM.OverloadedMethods;
7875}
7876
7877void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7878 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7879 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7880 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7881 PartialDiagnostic PD = PDiag(
7882 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7883 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7884 Diag(overloadedMD->getLocation(), PD);
7885 }
7886}
7887
7888/// Diagnose methods which overload virtual methods in a base class
7889/// without overriding any.
7890void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7891 if (MD->isInvalidDecl())
7892 return;
7893
7894 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7895 return;
7896
7897 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7898 FindHiddenVirtualMethods(MD, OverloadedMethods);
7899 if (!OverloadedMethods.empty()) {
7900 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7901 << MD << (OverloadedMethods.size() > 1);
7902
7903 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7904 }
7905}
7906
7907void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7908 auto PrintDiagAndRemoveAttr = [&]() {
7909 // No diagnostics if this is a template instantiation.
7910 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7911 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7912 diag::ext_cannot_use_trivial_abi) << &RD;
7913 RD.dropAttr<TrivialABIAttr>();
7914 };
7915
7916 // Ill-formed if the struct has virtual functions.
7917 if (RD.isPolymorphic()) {
7918 PrintDiagAndRemoveAttr();
7919 return;
7920 }
7921
7922 for (const auto &B : RD.bases()) {
7923 // Ill-formed if the base class is non-trivial for the purpose of calls or a
7924 // virtual base.
7925 if ((!B.getType()->isDependentType() &&
7926 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7927 B.isVirtual()) {
7928 PrintDiagAndRemoveAttr();
7929 return;
7930 }
7931 }
7932
7933 for (const auto *FD : RD.fields()) {
7934 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7935 // non-trivial for the purpose of calls.
7936 QualType FT = FD->getType();
7937 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7938 PrintDiagAndRemoveAttr();
7939 return;
7940 }
7941
7942 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7943 if (!RT->isDependentType() &&
7944 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7945 PrintDiagAndRemoveAttr();
7946 return;
7947 }
7948 }
7949}
7950
7951void Sema::ActOnFinishCXXMemberSpecification(
7952 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7953 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7954 if (!TagDecl)
7955 return;
7956
7957 AdjustDeclIfTemplate(TagDecl);
7958
7959 for (const ParsedAttr &AL : AttrList) {
7960 if (AL.getKind() != ParsedAttr::AT_Visibility)
7961 continue;
7962 AL.setInvalid();
7963 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7964 << AL.getName();
7965 }
7966
7967 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7968 // strict aliasing violation!
7969 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7970 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7971
7972 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7973}
7974
7975/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7976/// special functions, such as the default constructor, copy
7977/// constructor, or destructor, to the given C++ class (C++
7978/// [special]p1). This routine can only be executed just before the
7979/// definition of the class is complete.
7980void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7981 if (ClassDecl->needsImplicitDefaultConstructor()) {
7982 ++getASTContext().NumImplicitDefaultConstructors;
7983
7984 if (ClassDecl->hasInheritedConstructor())
7985 DeclareImplicitDefaultConstructor(ClassDecl);
7986 }
7987
7988 if (ClassDecl->needsImplicitCopyConstructor()) {
7989 ++getASTContext().NumImplicitCopyConstructors;
7990
7991 // If the properties or semantics of the copy constructor couldn't be
7992 // determined while the class was being declared, force a declaration
7993 // of it now.
7994 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7995 ClassDecl->hasInheritedConstructor())
7996 DeclareImplicitCopyConstructor(ClassDecl);
7997 // For the MS ABI we need to know whether the copy ctor is deleted. A
7998 // prerequisite for deleting the implicit copy ctor is that the class has a
7999 // move ctor or move assignment that is either user-declared or whose
8000 // semantics are inherited from a subobject. FIXME: We should provide a more
8001 // direct way for CodeGen to ask whether the constructor was deleted.
8002 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8003 (ClassDecl->hasUserDeclaredMoveConstructor() ||
8004 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8005 ClassDecl->hasUserDeclaredMoveAssignment() ||
8006 ClassDecl->needsOverloadResolutionForMoveAssignment()))
8007 DeclareImplicitCopyConstructor(ClassDecl);
8008 }
8009
8010 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8011 ++getASTContext().NumImplicitMoveConstructors;
8012
8013 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8014 ClassDecl->hasInheritedConstructor())
8015 DeclareImplicitMoveConstructor(ClassDecl);
8016 }
8017
8018 if (ClassDecl->needsImplicitCopyAssignment()) {
8019 ++getASTContext().NumImplicitCopyAssignmentOperators;
8020
8021 // If we have a dynamic class, then the copy assignment operator may be
8022 // virtual, so we have to declare it immediately. This ensures that, e.g.,
8023 // it shows up in the right place in the vtable and that we diagnose
8024 // problems with the implicit exception specification.
8025 if (ClassDecl->isDynamicClass() ||
8026 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8027 ClassDecl->hasInheritedAssignment())
8028 DeclareImplicitCopyAssignment(ClassDecl);
8029 }
8030
8031 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8032 ++getASTContext().NumImplicitMoveAssignmentOperators;
8033
8034 // Likewise for the move assignment operator.
8035 if (ClassDecl->isDynamicClass() ||
8036 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8037 ClassDecl->hasInheritedAssignment())
8038 DeclareImplicitMoveAssignment(ClassDecl);
8039 }
8040
8041 if (ClassDecl->needsImplicitDestructor()) {
8042 ++getASTContext().NumImplicitDestructors;
8043
8044 // If we have a dynamic class, then the destructor may be virtual, so we
8045 // have to declare the destructor immediately. This ensures that, e.g., it
8046 // shows up in the right place in the vtable and that we diagnose problems
8047 // with the implicit exception specification.
8048 if (ClassDecl->isDynamicClass() ||
8049 ClassDecl->needsOverloadResolutionForDestructor())
8050 DeclareImplicitDestructor(ClassDecl);
8051 }
8052}
8053
8054unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8055 if (!D)
8056 return 0;
8057
8058 // The order of template parameters is not important here. All names
8059 // get added to the same scope.
8060 SmallVector<TemplateParameterList *, 4> ParameterLists;
8061
8062 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8063 D = TD->getTemplatedDecl();
8064
8065 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8066 ParameterLists.push_back(PSD->getTemplateParameters());
8067
8068 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8069 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8070 ParameterLists.push_back(DD->getTemplateParameterList(i));
8071
8072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8073 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8074 ParameterLists.push_back(FTD->getTemplateParameters());
8075 }
8076 }
8077
8078 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8079 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8080 ParameterLists.push_back(TD->getTemplateParameterList(i));
8081
8082 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8083 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8084 ParameterLists.push_back(CTD->getTemplateParameters());
8085 }
8086 }
8087
8088 unsigned Count = 0;
8089 for (TemplateParameterList *Params : ParameterLists) {
8090 if (Params->size() > 0)
8091 // Ignore explicit specializations; they don't contribute to the template
8092 // depth.
8093 ++Count;
8094 for (NamedDecl *Param : *Params) {
8095 if (Param->getDeclName()) {
8096 S->AddDecl(Param);
8097 IdResolver.AddDecl(Param);
8098 }
8099 }
8100 }
8101
8102 return Count;
8103}
8104
8105void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8106 if (!RecordD) return;
8107 AdjustDeclIfTemplate(RecordD);
8108 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8109 PushDeclContext(S, Record);
8110}
8111
8112void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8113 if (!RecordD) return;
8114 PopDeclContext();
8115}
8116
8117/// This is used to implement the constant expression evaluation part of the
8118/// attribute enable_if extension. There is nothing in standard C++ which would
8119/// require reentering parameters.
8120void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8121 if (!Param)
8122 return;
8123
8124 S->AddDecl(Param);
8125 if (Param->getDeclName())
8126 IdResolver.AddDecl(Param);
8127}
8128
8129/// ActOnStartDelayedCXXMethodDeclaration - We have completed
8130/// parsing a top-level (non-nested) C++ class, and we are now
8131/// parsing those parts of the given Method declaration that could
8132/// not be parsed earlier (C++ [class.mem]p2), such as default
8133/// arguments. This action should enter the scope of the given
8134/// Method declaration as if we had just parsed the qualified method
8135/// name. However, it should not bring the parameters into scope;
8136/// that will be performed by ActOnDelayedCXXMethodParameter.
8137void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8138}
8139
8140/// ActOnDelayedCXXMethodParameter - We've already started a delayed
8141/// C++ method declaration. We're (re-)introducing the given
8142/// function parameter into scope for use in parsing later parts of
8143/// the method declaration. For example, we could see an
8144/// ActOnParamDefaultArgument event for this parameter.
8145void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8146 if (!ParamD)
8147 return;
8148
8149 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8150
8151 // If this parameter has an unparsed default argument, clear it out
8152 // to make way for the parsed default argument.
8153 if (Param->hasUnparsedDefaultArg())
8154 Param->setDefaultArg(nullptr);
8155
8156 S->AddDecl(Param);
8157 if (Param->getDeclName())
8158 IdResolver.AddDecl(Param);
8159}
8160
8161/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8162/// processing the delayed method declaration for Method. The method
8163/// declaration is now considered finished. There may be a separate
8164/// ActOnStartOfFunctionDef action later (not necessarily
8165/// immediately!) for this method, if it was also defined inside the
8166/// class body.
8167void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8168 if (!MethodD)
8169 return;
8170
8171 AdjustDeclIfTemplate(MethodD);
8172
8173 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8174
8175 // Now that we have our default arguments, check the constructor
8176 // again. It could produce additional diagnostics or affect whether
8177 // the class has implicitly-declared destructors, among other
8178 // things.
8179 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8180 CheckConstructor(Constructor);
8181
8182 // Check the default arguments, which we may have added.
8183 if (!Method->isInvalidDecl())
8184 CheckCXXDefaultArguments(Method);
8185}
8186
8187/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8188/// the well-formedness of the constructor declarator @p D with type @p
8189/// R. If there are any errors in the declarator, this routine will
8190/// emit diagnostics and set the invalid bit to true. In any case, the type
8191/// will be updated to reflect a well-formed type for the constructor and
8192/// returned.
8193QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8194 StorageClass &SC) {
8195 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8196
8197 // C++ [class.ctor]p3:
8198 // A constructor shall not be virtual (10.3) or static (9.4). A
8199 // constructor can be invoked for a const, volatile or const
8200 // volatile object. A constructor shall not be declared const,
8201 // volatile, or const volatile (9.3.2).
8202 if (isVirtual) {
8203 if (!D.isInvalidType())
8204 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8205 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8206 << SourceRange(D.getIdentifierLoc());
8207 D.setInvalidType();
8208 }
8209 if (SC == SC_Static) {
8210 if (!D.isInvalidType())
8211 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8212 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8213 << SourceRange(D.getIdentifierLoc());
8214 D.setInvalidType();
8215 SC = SC_None;
8216 }
8217
8218 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8219 diagnoseIgnoredQualifiers(
8220 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8221 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8222 D.getDeclSpec().getRestrictSpecLoc(),
8223 D.getDeclSpec().getAtomicSpecLoc());
8224 D.setInvalidType();
8225 }
8226
8227 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8228 if (FTI.hasMethodTypeQualifiers()) {
8229 FTI.MethodQualifiers->forEachQualifier(
8230 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8231 Diag(SL, diag::err_invalid_qualified_constructor)
8232 << QualName << SourceRange(SL);
8233 });
8234 D.setInvalidType();
8235 }
8236
8237 // C++0x [class.ctor]p4:
8238 // A constructor shall not be declared with a ref-qualifier.
8239 if (FTI.hasRefQualifier()) {
8240 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8241 << FTI.RefQualifierIsLValueRef
8242 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8243 D.setInvalidType();
8244 }
8245
8246 // Rebuild the function type "R" without any type qualifiers (in
8247 // case any of the errors above fired) and with "void" as the
8248 // return type, since constructors don't have return types.
8249 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8250 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8251 return R;
8252
8253 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8254 EPI.TypeQuals = Qualifiers();
8255 EPI.RefQualifier = RQ_None;
8256
8257 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8258}
8259
8260/// CheckConstructor - Checks a fully-formed constructor for
8261/// well-formedness, issuing any diagnostics required. Returns true if
8262/// the constructor declarator is invalid.
8263void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8264 CXXRecordDecl *ClassDecl
8265 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8266 if (!ClassDecl)
8267 return Constructor->setInvalidDecl();
8268
8269 // C++ [class.copy]p3:
8270 // A declaration of a constructor for a class X is ill-formed if
8271 // its first parameter is of type (optionally cv-qualified) X and
8272 // either there are no other parameters or else all other
8273 // parameters have default arguments.
8274 if (!Constructor->isInvalidDecl() &&
8275 ((Constructor->getNumParams() == 1) ||
8276 (Constructor->getNumParams() > 1 &&
8277 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8278 Constructor->getTemplateSpecializationKind()
8279 != TSK_ImplicitInstantiation) {
8280 QualType ParamType = Constructor->getParamDecl(0)->getType();
8281 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8282 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8283 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8284 const char *ConstRef
8285 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8286 : " const &";
8287 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8288 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8289
8290 // FIXME: Rather that making the constructor invalid, we should endeavor
8291 // to fix the type.
8292 Constructor->setInvalidDecl();
8293 }
8294 }
8295}
8296
8297/// CheckDestructor - Checks a fully-formed destructor definition for
8298/// well-formedness, issuing any diagnostics required. Returns true
8299/// on error.
8300bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8301 CXXRecordDecl *RD = Destructor->getParent();
8302
8303 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8304 SourceLocation Loc;
8305
8306 if (!Destructor->isImplicit())
8307 Loc = Destructor->getLocation();
8308 else
8309 Loc = RD->getLocation();
8310
8311 // If we have a virtual destructor, look up the deallocation function
8312 if (FunctionDecl *OperatorDelete =
8313 FindDeallocationFunctionForDestructor(Loc, RD)) {
8314 Expr *ThisArg = nullptr;
8315
8316 // If the notional 'delete this' expression requires a non-trivial
8317 // conversion from 'this' to the type of a destroying operator delete's
8318 // first parameter, perform that conversion now.
8319 if (OperatorDelete->isDestroyingOperatorDelete()) {
8320 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8321 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8322 // C++ [class.dtor]p13:
8323 // ... as if for the expression 'delete this' appearing in a
8324 // non-virtual destructor of the destructor's class.
8325 ContextRAII SwitchContext(*this, Destructor);
8326 ExprResult This =
8327 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8328 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8329 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8330 if (This.isInvalid()) {
8331 // FIXME: Register this as a context note so that it comes out
8332 // in the right order.
8333 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8334 return true;
8335 }
8336 ThisArg = This.get();
8337 }
8338 }
8339
8340 DiagnoseUseOfDecl(OperatorDelete, Loc);
8341 MarkFunctionReferenced(Loc, OperatorDelete);
8342 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8343 }
8344 }
8345
8346 return false;
8347}
8348
8349/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8350/// the well-formednes of the destructor declarator @p D with type @p
8351/// R. If there are any errors in the declarator, this routine will
8352/// emit diagnostics and set the declarator to invalid. Even if this happens,
8353/// will be updated to reflect a well-formed type for the destructor and
8354/// returned.
8355QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8356 StorageClass& SC) {
8357 // C++ [class.dtor]p1:
8358 // [...] A typedef-name that names a class is a class-name
8359 // (7.1.3); however, a typedef-name that names a class shall not
8360 // be used as the identifier in the declarator for a destructor
8361 // declaration.
8362 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8363 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8364 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8365 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8366 else if (const TemplateSpecializationType *TST =
8367 DeclaratorType->getAs<TemplateSpecializationType>())
8368 if (TST->isTypeAlias())
8369 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8370 << DeclaratorType << 1;
8371
8372 // C++ [class.dtor]p2:
8373 // A destructor is used to destroy objects of its class type. A
8374 // destructor takes no parameters, and no return type can be
8375 // specified for it (not even void). The address of a destructor
8376 // shall not be taken. A destructor shall not be static. A
8377 // destructor can be invoked for a const, volatile or const
8378 // volatile object. A destructor shall not be declared const,
8379 // volatile or const volatile (9.3.2).
8380 if (SC == SC_Static) {
8381 if (!D.isInvalidType())
8382 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8383 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8384 << SourceRange(D.getIdentifierLoc())
8385 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8386
8387 SC = SC_None;
8388 }
8389 if (!D.isInvalidType()) {
8390 // Destructors don't have return types, but the parser will
8391 // happily parse something like:
8392 //
8393 // class X {
8394 // float ~X();
8395 // };
8396 //
8397 // The return type will be eliminated later.
8398 if (D.getDeclSpec().hasTypeSpecifier())
8399 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8400 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8401 << SourceRange(D.getIdentifierLoc());
8402 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8403 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8404 SourceLocation(),
8405 D.getDeclSpec().getConstSpecLoc(),
8406 D.getDeclSpec().getVolatileSpecLoc(),
8407 D.getDeclSpec().getRestrictSpecLoc(),
8408 D.getDeclSpec().getAtomicSpecLoc());
8409 D.setInvalidType();
8410 }
8411 }
8412
8413 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8414 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8415 FTI.MethodQualifiers->forEachQualifier(
8416 [&](DeclSpec::TQ TypeQual, StringRef QualName, SourceLocation SL) {
8417 Diag(SL, diag::err_invalid_qualified_destructor)
8418 << QualName << SourceRange(SL);
8419 });
8420 D.setInvalidType();
8421 }
8422
8423 // C++0x [class.dtor]p2:
8424 // A destructor shall not be declared with a ref-qualifier.
8425 if (FTI.hasRefQualifier()) {
8426 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8427 << FTI.RefQualifierIsLValueRef
8428 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8429 D.setInvalidType();
8430 }
8431
8432 // Make sure we don't have any parameters.
8433 if (FTIHasNonVoidParameters(FTI)) {
8434 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8435
8436 // Delete the parameters.
8437 FTI.freeParams();
8438 D.setInvalidType();
8439 }
8440
8441 // Make sure the destructor isn't variadic.
8442 if (FTI.isVariadic) {
8443 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8444 D.setInvalidType();
8445 }
8446
8447 // Rebuild the function type "R" without any type qualifiers or
8448 // parameters (in case any of the errors above fired) and with
8449 // "void" as the return type, since destructors don't have return
8450 // types.
8451 if (!D.isInvalidType())
8452 return R;
8453
8454 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8455 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8456 EPI.Variadic = false;
8457 EPI.TypeQuals = Qualifiers();
8458 EPI.RefQualifier = RQ_None;
8459 return Context.getFunctionType(Context.VoidTy, None, EPI);
8460}
8461
8462static void extendLeft(SourceRange &R, SourceRange Before) {
8463 if (Before.isInvalid())
8464 return;
8465 R.setBegin(Before.getBegin());
8466 if (R.getEnd().isInvalid())
8467 R.setEnd(Before.getEnd());
8468}
8469
8470static void extendRight(SourceRange &R, SourceRange After) {
8471 if (After.isInvalid())
8472 return;
8473 if (R.getBegin().isInvalid())
8474 R.setBegin(After.getBegin());
8475 R.setEnd(After.getEnd());
8476}
8477
8478/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8479/// well-formednes of the conversion function declarator @p D with
8480/// type @p R. If there are any errors in the declarator, this routine
8481/// will emit diagnostics and return true. Otherwise, it will return
8482/// false. Either way, the type @p R will be updated to reflect a
8483/// well-formed type for the conversion operator.
8484void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8485 StorageClass& SC) {
8486 // C++ [class.conv.fct]p1:
8487 // Neither parameter types nor return type can be specified. The
8488 // type of a conversion function (8.3.5) is "function taking no
8489 // parameter returning conversion-type-id."
8490 if (SC == SC_Static) {
8491 if (!D.isInvalidType())
8492 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8493 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8494 << D.getName().getSourceRange();
8495 D.setInvalidType();
8496 SC = SC_None;
8497 }
8498
8499 TypeSourceInfo *ConvTSI = nullptr;
8500 QualType ConvType =
8501 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8502
8503 const DeclSpec &DS = D.getDeclSpec();
8504 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8505 // Conversion functions don't have return types, but the parser will
8506 // happily parse something like:
8507 //
8508 // class X {
8509 // float operator bool();
8510 // };
8511 //
8512 // The return type will be changed later anyway.
8513 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8514 << SourceRange(DS.getTypeSpecTypeLoc())
8515 << SourceRange(D.getIdentifierLoc());
8516 D.setInvalidType();
8517 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8518 // It's also plausible that the user writes type qualifiers in the wrong
8519 // place, such as:
8520 // struct S { const operator int(); };
8521 // FIXME: we could provide a fixit to move the qualifiers onto the
8522 // conversion type.
8523 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8524 << SourceRange(D.getIdentifierLoc()) << 0;
8525 D.setInvalidType();
8526 }
8527
8528 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8529
8530 // Make sure we don't have any parameters.
8531 if (Proto->getNumParams() > 0) {
8532 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8533
8534 // Delete the parameters.
8535 D.getFunctionTypeInfo().freeParams();
8536 D.setInvalidType();
8537 } else if (Proto->isVariadic()) {
8538 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8539 D.setInvalidType();
8540 }
8541
8542 // Diagnose "&operator bool()" and other such nonsense. This
8543 // is actually a gcc extension which we don't support.
8544 if (Proto->getReturnType() != ConvType) {
8545 bool NeedsTypedef = false;
8546 SourceRange Before, After;
8547
8548 // Walk the chunks and extract information on them for our diagnostic.
8549 bool PastFunctionChunk = false;
8550 for (auto &Chunk : D.type_objects()) {
8551 switch (Chunk.Kind) {
8552 case DeclaratorChunk::Function:
8553 if (!PastFunctionChunk) {
8554 if (Chunk.Fun.HasTrailingReturnType) {
8555 TypeSourceInfo *TRT = nullptr;
8556 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8557 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8558 }
8559 PastFunctionChunk = true;
8560 break;
8561 }
8562 LLVM_FALLTHROUGH;
8563 case DeclaratorChunk::Array:
8564 NeedsTypedef = true;
8565 extendRight(After, Chunk.getSourceRange());
8566 break;
8567
8568 case DeclaratorChunk::Pointer:
8569 case DeclaratorChunk::BlockPointer:
8570 case DeclaratorChunk::Reference:
8571 case DeclaratorChunk::MemberPointer:
8572 case DeclaratorChunk::Pipe:
8573 extendLeft(Before, Chunk.getSourceRange());
8574 break;
8575
8576 case DeclaratorChunk::Paren:
8577 extendLeft(Before, Chunk.Loc);
8578 extendRight(After, Chunk.EndLoc);
8579 break;
8580 }
8581 }
8582
8583 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8584 After.isValid() ? After.getBegin() :
8585 D.getIdentifierLoc();
8586 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8587 DB << Before << After;
8588
8589 if (!NeedsTypedef) {
8590 DB << /*don't need a typedef*/0;
8591
8592 // If we can provide a correct fix-it hint, do so.
8593 if (After.isInvalid() && ConvTSI) {
8594 SourceLocation InsertLoc =
8595 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8596 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8597 << FixItHint::CreateInsertionFromRange(
8598 InsertLoc, CharSourceRange::getTokenRange(Before))
8599 << FixItHint::CreateRemoval(Before);
8600 }
8601 } else if (!Proto->getReturnType()->isDependentType()) {
8602 DB << /*typedef*/1 << Proto->getReturnType();
8603 } else if (getLangOpts().CPlusPlus11) {
8604 DB << /*alias template*/2 << Proto->getReturnType();
8605 } else {
8606 DB << /*might not be fixable*/3;
8607 }
8608
8609 // Recover by incorporating the other type chunks into the result type.
8610 // Note, this does *not* change the name of the function. This is compatible
8611 // with the GCC extension:
8612 // struct S { &operator int(); } s;
8613 // int &r = s.operator int(); // ok in GCC
8614 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8615 ConvType = Proto->getReturnType();
8616 }
8617
8618 // C++ [class.conv.fct]p4:
8619 // The conversion-type-id shall not represent a function type nor
8620 // an array type.
8621 if (ConvType->isArrayType()) {
8622 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8623 ConvType = Context.getPointerType(ConvType);
8624 D.setInvalidType();
8625 } else if (ConvType->isFunctionType()) {
8626 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8627 ConvType = Context.getPointerType(ConvType);
8628 D.setInvalidType();
8629 }
8630
8631 // Rebuild the function type "R" without any parameters (in case any
8632 // of the errors above fired) and with the conversion type as the
8633 // return type.
8634 if (D.isInvalidType())
8635 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8636
8637 // C++0x explicit conversion operators.
8638 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8639 Diag(DS.getExplicitSpecLoc(),
8640 getLangOpts().CPlusPlus11
8641 ? diag::warn_cxx98_compat_explicit_conversion_functions
8642 : diag::ext_explicit_conversion_functions)
8643 << SourceRange(DS.getExplicitSpecRange());
8644}
8645
8646/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8647/// the declaration of the given C++ conversion function. This routine
8648/// is responsible for recording the conversion function in the C++
8649/// class, if possible.
8650Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8651 assert(Conversion && "Expected to receive a conversion function declaration");
8652
8653 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8654
8655 // Make sure we aren't redeclaring the conversion function.
8656 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8657
8658 // C++ [class.conv.fct]p1:
8659 // [...] A conversion function is never used to convert a
8660 // (possibly cv-qualified) object to the (possibly cv-qualified)
8661 // same object type (or a reference to it), to a (possibly
8662 // cv-qualified) base class of that type (or a reference to it),
8663 // or to (possibly cv-qualified) void.
8664 // FIXME: Suppress this warning if the conversion function ends up being a
8665 // virtual function that overrides a virtual function in a base class.
8666 QualType ClassType
8667 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8668 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8669 ConvType = ConvTypeRef->getPointeeType();
8670 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8671 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8672 /* Suppress diagnostics for instantiations. */;
8673 else if (ConvType->isRecordType()) {
8674 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8675 if (ConvType == ClassType)
8676 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8677 << ClassType;
8678 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8679 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8680 << ClassType << ConvType;
8681 } else if (ConvType->isVoidType()) {
8682 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8683 << ClassType << ConvType;
8684 }
8685
8686 if (FunctionTemplateDecl *ConversionTemplate
8687 = Conversion->getDescribedFunctionTemplate())
8688 return ConversionTemplate;
8689
8690 return Conversion;
8691}
8692
8693namespace {
8694/// Utility class to accumulate and print a diagnostic listing the invalid
8695/// specifier(s) on a declaration.
8696struct BadSpecifierDiagnoser {
8697 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8698 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8699 ~BadSpecifierDiagnoser() {
8700 Diagnostic << Specifiers;
8701 }
8702
8703 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8704 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8705 }
8706 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8707 return check(SpecLoc,
8708 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8709 }
8710 void check(SourceLocation SpecLoc, const char *Spec) {
8711 if (SpecLoc.isInvalid()) return;
8712 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8713 if (!Specifiers.empty()) Specifiers += " ";
8714 Specifiers += Spec;
8715 }
8716
8717 Sema &S;
8718 Sema::SemaDiagnosticBuilder Diagnostic;
8719 std::string Specifiers;
8720};
8721}
8722
8723/// Check the validity of a declarator that we parsed for a deduction-guide.
8724/// These aren't actually declarators in the grammar, so we need to check that
8725/// the user didn't specify any pieces that are not part of the deduction-guide
8726/// grammar.
8727void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8728 StorageClass &SC) {
8729 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8730 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8731 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8732
8733 // C++ [temp.deduct.guide]p3:
8734 // A deduction-gide shall be declared in the same scope as the
8735 // corresponding class template.
8736 if (!CurContext->getRedeclContext()->Equals(
8737 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8738 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8739 << GuidedTemplateDecl;
8740 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8741 }
8742
8743 auto &DS = D.getMutableDeclSpec();
8744 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8745 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8746 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8747 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8748 BadSpecifierDiagnoser Diagnoser(
8749 *this, D.getIdentifierLoc(),
8750 diag::err_deduction_guide_invalid_specifier);
8751
8752 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8753 DS.ClearStorageClassSpecs();
8754 SC = SC_None;
8755
8756 // 'explicit' is permitted.
8757 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8758 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8759 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8760 DS.ClearConstexprSpec();
8761
8762 Diagnoser.check(DS.getConstSpecLoc(), "const");
8763 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8764 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8765 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8766 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8767 DS.ClearTypeQualifiers();
8768
8769 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8770 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8771 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8772 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8773 DS.ClearTypeSpecType();
8774 }
8775
8776 if (D.isInvalidType())
8777 return;
8778
8779 // Check the declarator is simple enough.
8780 bool FoundFunction = false;
8781 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8782 if (Chunk.Kind == DeclaratorChunk::Paren)
8783 continue;
8784 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8785 Diag(D.getDeclSpec().getBeginLoc(),
8786 diag::err_deduction_guide_with_complex_decl)
8787 << D.getSourceRange();
8788 break;
8789 }
8790 if (!Chunk.Fun.hasTrailingReturnType()) {
8791 Diag(D.getName().getBeginLoc(),
8792 diag::err_deduction_guide_no_trailing_return_type);
8793 break;
8794 }
8795
8796 // Check that the return type is written as a specialization of
8797 // the template specified as the deduction-guide's name.
8798 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8799 TypeSourceInfo *TSI = nullptr;
8800 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8801 assert(TSI && "deduction guide has valid type but invalid return type?");
8802 bool AcceptableReturnType = false;
8803 bool MightInstantiateToSpecialization = false;
8804 if (auto RetTST =
8805 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8806 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8807 bool TemplateMatches =
8808 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8809 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8810 AcceptableReturnType = true;
8811 else {
8812 // This could still instantiate to the right type, unless we know it
8813 // names the wrong class template.
8814 auto *TD = SpecifiedName.getAsTemplateDecl();
8815 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8816 !TemplateMatches);
8817 }
8818 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8819 MightInstantiateToSpecialization = true;
8820 }
8821
8822 if (!AcceptableReturnType) {
8823 Diag(TSI->getTypeLoc().getBeginLoc(),
8824 diag::err_deduction_guide_bad_trailing_return_type)
8825 << GuidedTemplate << TSI->getType()
8826 << MightInstantiateToSpecialization
8827 << TSI->getTypeLoc().getSourceRange();
8828 }
8829
8830 // Keep going to check that we don't have any inner declarator pieces (we
8831 // could still have a function returning a pointer to a function).
8832 FoundFunction = true;
8833 }
8834
8835 if (D.isFunctionDefinition())
8836 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8837}
8838
8839//===----------------------------------------------------------------------===//
8840// Namespace Handling
8841//===----------------------------------------------------------------------===//
8842
8843/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8844/// reopened.
8845static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8846 SourceLocation Loc,
8847 IdentifierInfo *II, bool *IsInline,
8848 NamespaceDecl *PrevNS) {
8849 assert(*IsInline != PrevNS->isInline());
8850
8851 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8852 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8853 // inline namespaces, with the intention of bringing names into namespace std.
8854 //
8855 // We support this just well enough to get that case working; this is not
8856 // sufficient to support reopening namespaces as inline in general.
8857 if (*IsInline && II && II->getName().startswith("__atomic") &&
8858 S.getSourceManager().isInSystemHeader(Loc)) {
8859 // Mark all prior declarations of the namespace as inline.
8860 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8861 NS = NS->getPreviousDecl())
8862 NS->setInline(*IsInline);
8863 // Patch up the lookup table for the containing namespace. This isn't really
8864 // correct, but it's good enough for this particular case.
8865 for (auto *I : PrevNS->decls())
8866 if (auto *ND = dyn_cast<NamedDecl>(I))
8867 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8868 return;
8869 }
8870
8871 if (PrevNS->isInline())
8872 // The user probably just forgot the 'inline', so suggest that it
8873 // be added back.
8874 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8875 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8876 else
8877 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8878
8879 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8880 *IsInline = PrevNS->isInline();
8881}
8882
8883/// ActOnStartNamespaceDef - This is called at the start of a namespace
8884/// definition.
8885Decl *Sema::ActOnStartNamespaceDef(
8886 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8887 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8888 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8889 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8890 // For anonymous namespace, take the location of the left brace.
8891 SourceLocation Loc = II ? IdentLoc : LBrace;
8892 bool IsInline = InlineLoc.isValid();
8893 bool IsInvalid = false;
8894 bool IsStd = false;
8895 bool AddToKnown = false;
8896 Scope *DeclRegionScope = NamespcScope->getParent();
8897
8898 NamespaceDecl *PrevNS = nullptr;
8899 if (II) {
8900 // C++ [namespace.def]p2:
8901 // The identifier in an original-namespace-definition shall not
8902 // have been previously defined in the declarative region in
8903 // which the original-namespace-definition appears. The
8904 // identifier in an original-namespace-definition is the name of
8905 // the namespace. Subsequently in that declarative region, it is
8906 // treated as an original-namespace-name.
8907 //
8908 // Since namespace names are unique in their scope, and we don't
8909 // look through using directives, just look for any ordinary names
8910 // as if by qualified name lookup.
8911 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8912 ForExternalRedeclaration);
8913 LookupQualifiedName(R, CurContext->getRedeclContext());
8914 NamedDecl *PrevDecl =
8915 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8916 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8917
8918 if (PrevNS) {
8919 // This is an extended namespace definition.
8920 if (IsInline != PrevNS->isInline())
8921 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8922 &IsInline, PrevNS);
8923 } else if (PrevDecl) {
8924 // This is an invalid name redefinition.
8925 Diag(Loc, diag::err_redefinition_different_kind)
8926 << II;
8927 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8928 IsInvalid = true;
8929 // Continue on to push Namespc as current DeclContext and return it.
8930 } else if (II->isStr("std") &&
8931 CurContext->getRedeclContext()->isTranslationUnit()) {
8932 // This is the first "real" definition of the namespace "std", so update
8933 // our cache of the "std" namespace to point at this definition.
8934 PrevNS = getStdNamespace();
8935 IsStd = true;
8936 AddToKnown = !IsInline;
8937 } else {
8938 // We've seen this namespace for the first time.
8939 AddToKnown = !IsInline;
8940 }
8941 } else {
8942 // Anonymous namespaces.
8943
8944 // Determine whether the parent already has an anonymous namespace.
8945 DeclContext *Parent = CurContext->getRedeclContext();
8946 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8947 PrevNS = TU->getAnonymousNamespace();
8948 } else {
8949 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8950 PrevNS = ND->getAnonymousNamespace();
8951 }
8952
8953 if (PrevNS && IsInline != PrevNS->isInline())
8954 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8955 &IsInline, PrevNS);
8956 }
8957
8958 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8959 StartLoc, Loc, II, PrevNS);
8960 if (IsInvalid)
8961 Namespc->setInvalidDecl();
8962
8963 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8964 AddPragmaAttributes(DeclRegionScope, Namespc);
8965
8966 // FIXME: Should we be merging attributes?
8967 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8968 PushNamespaceVisibilityAttr(Attr, Loc);
8969
8970 if (IsStd)
8971 StdNamespace = Namespc;
8972 if (AddToKnown)
8973 KnownNamespaces[Namespc] = false;
8974
8975 if (II) {
8976 PushOnScopeChains(Namespc, DeclRegionScope);
8977 } else {
8978 // Link the anonymous namespace into its parent.
8979 DeclContext *Parent = CurContext->getRedeclContext();
8980 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8981 TU->setAnonymousNamespace(Namespc);
8982 } else {
8983 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8984 }
8985
8986 CurContext->addDecl(Namespc);
8987
8988 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8989 // behaves as if it were replaced by
8990 // namespace unique { /* empty body */ }
8991 // using namespace unique;
8992 // namespace unique { namespace-body }
8993 // where all occurrences of 'unique' in a translation unit are
8994 // replaced by the same identifier and this identifier differs
8995 // from all other identifiers in the entire program.
8996
8997 // We just create the namespace with an empty name and then add an
8998 // implicit using declaration, just like the standard suggests.
8999 //
9000 // CodeGen enforces the "universally unique" aspect by giving all
9001 // declarations semantically contained within an anonymous
9002 // namespace internal linkage.
9003
9004 if (!PrevNS) {
9005 UD = UsingDirectiveDecl::Create(Context, Parent,
9006 /* 'using' */ LBrace,
9007 /* 'namespace' */ SourceLocation(),
9008 /* qualifier */ NestedNameSpecifierLoc(),
9009 /* identifier */ SourceLocation(),
9010 Namespc,
9011 /* Ancestor */ Parent);
9012 UD->setImplicit();
9013 Parent->addDecl(UD);
9014 }
9015 }
9016
9017 ActOnDocumentableDecl(Namespc);
9018
9019 // Although we could have an invalid decl (i.e. the namespace name is a
9020 // redefinition), push it as current DeclContext and try to continue parsing.
9021 // FIXME: We should be able to push Namespc here, so that the each DeclContext
9022 // for the namespace has the declarations that showed up in that particular
9023 // namespace definition.
9024 PushDeclContext(NamespcScope, Namespc);
9025 return Namespc;
9026}
9027
9028/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9029/// is a namespace alias, returns the namespace it points to.
9030static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9031 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9032 return AD->getNamespace();
9033 return dyn_cast_or_null<NamespaceDecl>(D);
9034}
9035
9036/// ActOnFinishNamespaceDef - This callback is called after a namespace is
9037/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9038void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9039 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9040 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9041 Namespc->setRBraceLoc(RBrace);
9042 PopDeclContext();
9043 if (Namespc->hasAttr<VisibilityAttr>())
9044 PopPragmaVisibility(true, RBrace);
9045 // If this namespace contains an export-declaration, export it now.
9046 if (DeferredExportedNamespaces.erase(Namespc))
9047 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9048}
9049
9050CXXRecordDecl *Sema::getStdBadAlloc() const {
9051 return cast_or_null<CXXRecordDecl>(
9052 StdBadAlloc.get(Context.getExternalSource()));
9053}
9054
9055EnumDecl *Sema::getStdAlignValT() const {
9056 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9057}
9058
9059NamespaceDecl *Sema::getStdNamespace() const {
9060 return cast_or_null<NamespaceDecl>(
9061 StdNamespace.get(Context.getExternalSource()));
9062}
9063
9064NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9065 if (!StdExperimentalNamespaceCache) {
9066 if (auto Std = getStdNamespace()) {
9067 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9068 SourceLocation(), LookupNamespaceName);
9069 if (!LookupQualifiedName(Result, Std) ||
9070 !(StdExperimentalNamespaceCache =
9071 Result.getAsSingle<NamespaceDecl>()))
9072 Result.suppressDiagnostics();
9073 }
9074 }
9075 return StdExperimentalNamespaceCache;
9076}
9077
9078namespace {
9079
9080enum UnsupportedSTLSelect {
9081 USS_InvalidMember,
9082 USS_MissingMember,
9083 USS_NonTrivial,
9084 USS_Other
9085};
9086
9087struct InvalidSTLDiagnoser {
9088 Sema &S;
9089 SourceLocation Loc;
9090 QualType TyForDiags;
9091
9092 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9093 const VarDecl *VD = nullptr) {
9094 {
9095 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9096 << TyForDiags << ((int)Sel);
9097 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9098 assert(!Name.empty());
9099 D << Name;
9100 }
9101 }
9102 if (Sel == USS_InvalidMember) {
9103 S.Diag(VD->getLocation(), diag::note_var_declared_here)
9104 << VD << VD->getSourceRange();
9105 }
9106 return QualType();
9107 }
9108};
9109} // namespace
9110
9111QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9112 SourceLocation Loc) {
9113 assert(getLangOpts().CPlusPlus &&
9114 "Looking for comparison category type outside of C++.");
9115
9116 // Check if we've already successfully checked the comparison category type
9117 // before. If so, skip checking it again.
9118 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9119 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9120 return Info->getType();
9121
9122 // If lookup failed
9123 if (!Info) {
9124 std::string NameForDiags = "std::";
9125 NameForDiags += ComparisonCategories::getCategoryString(Kind);
9126 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9127 << NameForDiags;
9128 return QualType();
9129 }
9130
9131 assert(Info->Kind == Kind);
9132 assert(Info->Record);
9133
9134 // Update the Record decl in case we encountered a forward declaration on our
9135 // first pass. FIXME: This is a bit of a hack.
9136 if (Info->Record->hasDefinition())
9137 Info->Record = Info->Record->getDefinition();
9138
9139 // Use an elaborated type for diagnostics which has a name containing the
9140 // prepended 'std' namespace but not any inline namespace names.
9141 QualType TyForDiags = [&]() {
9142 auto *NNS =
9143 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9144 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9145 }();
9146
9147 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9148 return QualType();
9149
9150 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9151
9152 if (!Info->Record->isTriviallyCopyable())
9153 return UnsupportedSTLError(USS_NonTrivial);
9154
9155 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9156 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9157 // Tolerate empty base classes.
9158 if (Base->isEmpty())
9159 continue;
9160 // Reject STL implementations which have at least one non-empty base.
9161 return UnsupportedSTLError();
9162 }
9163
9164 // Check that the STL has implemented the types using a single integer field.
9165 // This expectation allows better codegen for builtin operators. We require:
9166 // (1) The class has exactly one field.
9167 // (2) The field is an integral or enumeration type.
9168 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9169 if (std::distance(FIt, FEnd) != 1 ||
9170 !FIt->getType()->isIntegralOrEnumerationType()) {
9171 return UnsupportedSTLError();
9172 }
9173
9174 // Build each of the require values and store them in Info.
9175 for (ComparisonCategoryResult CCR :
9176 ComparisonCategories::getPossibleResultsForType(Kind)) {
9177 StringRef MemName = ComparisonCategories::getResultString(CCR);
9178 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9179
9180 if (!ValInfo)
9181 return UnsupportedSTLError(USS_MissingMember, MemName);
9182
9183 VarDecl *VD = ValInfo->VD;
9184 assert(VD && "should not be null!");
9185
9186 // Attempt to diagnose reasons why the STL definition of this type
9187 // might be foobar, including it failing to be a constant expression.
9188 // TODO Handle more ways the lookup or result can be invalid.
9189 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9190 !VD->checkInitIsICE())
9191 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9192
9193 // Attempt to evaluate the var decl as a constant expression and extract
9194 // the value of its first field as a ICE. If this fails, the STL
9195 // implementation is not supported.
9196 if (!ValInfo->hasValidIntValue())
9197 return UnsupportedSTLError();
9198
9199 MarkVariableReferenced(Loc, VD);
9200 }
9201
9202 // We've successfully built the required types and expressions. Update
9203 // the cache and return the newly cached value.
9204 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9205 return Info->getType();
9206}
9207
9208/// Retrieve the special "std" namespace, which may require us to
9209/// implicitly define the namespace.
9210NamespaceDecl *Sema::getOrCreateStdNamespace() {
9211 if (!StdNamespace) {
9212 // The "std" namespace has not yet been defined, so build one implicitly.
9213 StdNamespace = NamespaceDecl::Create(Context,
9214 Context.getTranslationUnitDecl(),
9215 /*Inline=*/false,
9216 SourceLocation(), SourceLocation(),
9217 &PP.getIdentifierTable().get("std"),
9218 /*PrevDecl=*/nullptr);
9219 getStdNamespace()->setImplicit(true);
9220 }
9221
9222 return getStdNamespace();
9223}
9224
9225bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9226 assert(getLangOpts().CPlusPlus &&
9227 "Looking for std::initializer_list outside of C++.");
9228
9229 // We're looking for implicit instantiations of
9230 // template <typename E> class std::initializer_list.
9231
9232 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9233 return false;
9234
9235 ClassTemplateDecl *Template = nullptr;
9236 const TemplateArgument *Arguments = nullptr;
9237
9238 if (const RecordType *RT = Ty->getAs<RecordType>()) {
9239
9240 ClassTemplateSpecializationDecl *Specialization =
9241 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9242 if (!Specialization)
9243 return false;
9244
9245 Template = Specialization->getSpecializedTemplate();
9246 Arguments = Specialization->getTemplateArgs().data();
9247 } else if (const TemplateSpecializationType *TST =
9248 Ty->getAs<TemplateSpecializationType>()) {
9249 Template = dyn_cast_or_null<ClassTemplateDecl>(
9250 TST->getTemplateName().getAsTemplateDecl());
9251 Arguments = TST->getArgs();
9252 }
9253 if (!Template)
9254 return false;
9255
9256 if (!StdInitializerList) {
9257 // Haven't recognized std::initializer_list yet, maybe this is it.
9258 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9259 if (TemplateClass->getIdentifier() !=
9260 &PP.getIdentifierTable().get("initializer_list") ||
9261 !getStdNamespace()->InEnclosingNamespaceSetOf(
9262 TemplateClass->getDeclContext()))
9263 return false;
9264 // This is a template called std::initializer_list, but is it the right
9265 // template?
9266 TemplateParameterList *Params = Template->getTemplateParameters();
9267 if (Params->getMinRequiredArguments() != 1)
9268 return false;
9269 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9270 return false;
9271
9272 // It's the right template.
9273 StdInitializerList = Template;
9274 }
9275
9276 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9277 return false;
9278
9279 // This is an instance of std::initializer_list. Find the argument type.
9280 if (Element)
9281 *Element = Arguments[0].getAsType();
9282 return true;
9283}
9284
9285static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9286 NamespaceDecl *Std = S.getStdNamespace();
9287 if (!Std) {
9288 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9289 return nullptr;
9290 }
9291
9292 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9293 Loc, Sema::LookupOrdinaryName);
9294 if (!S.LookupQualifiedName(Result, Std)) {
9295 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9296 return nullptr;
9297 }
9298 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9299 if (!Template) {
9300 Result.suppressDiagnostics();
9301 // We found something weird. Complain about the first thing we found.
9302 NamedDecl *Found = *Result.begin();
9303 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9304 return nullptr;
9305 }
9306
9307 // We found some template called std::initializer_list. Now verify that it's
9308 // correct.
9309 TemplateParameterList *Params = Template->getTemplateParameters();
9310 if (Params->getMinRequiredArguments() != 1 ||
9311 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9312 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9313 return nullptr;
9314 }
9315
9316 return Template;
9317}
9318
9319QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9320 if (!StdInitializerList) {
9321 StdInitializerList = LookupStdInitializerList(*this, Loc);
9322 if (!StdInitializerList)
9323 return QualType();
9324 }
9325
9326 TemplateArgumentListInfo Args(Loc, Loc);
9327 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9328 Context.getTrivialTypeSourceInfo(Element,
9329 Loc)));
9330 return Context.getCanonicalType(
9331 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9332}
9333
9334bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9335 // C++ [dcl.init.list]p2:
9336 // A constructor is an initializer-list constructor if its first parameter
9337 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9338 // std::initializer_list<E> for some type E, and either there are no other
9339 // parameters or else all other parameters have default arguments.
9340 if (Ctor->getNumParams() < 1 ||
9341 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9342 return false;
9343
9344 QualType ArgType = Ctor->getParamDecl(0)->getType();
9345 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9346 ArgType = RT->getPointeeType().getUnqualifiedType();
9347
9348 return isStdInitializerList(ArgType, nullptr);
9349}
9350
9351/// Determine whether a using statement is in a context where it will be
9352/// apply in all contexts.
9353static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9354 switch (CurContext->getDeclKind()) {
9355 case Decl::TranslationUnit:
9356 return true;
9357 case Decl::LinkageSpec:
9358 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9359 default:
9360 return false;
9361 }
9362}
9363
9364namespace {
9365
9366// Callback to only accept typo corrections that are namespaces.
9367class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9368public:
9369 bool ValidateCandidate(const TypoCorrection &candidate) override {
9370 if (NamedDecl *ND = candidate.getCorrectionDecl())
9371 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9372 return false;
9373 }
9374
9375 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9376 return llvm::make_unique<NamespaceValidatorCCC>(*this);
9377 }
9378};
9379
9380}
9381
9382static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9383 CXXScopeSpec &SS,
9384 SourceLocation IdentLoc,
9385 IdentifierInfo *Ident) {
9386 R.clear();
9387 NamespaceValidatorCCC CCC{};
9388 if (TypoCorrection Corrected =
9389 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9390 Sema::CTK_ErrorRecovery)) {
9391 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9392 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9393 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9394 Ident->getName().equals(CorrectedStr);
9395 S.diagnoseTypo(Corrected,
9396 S.PDiag(diag::err_using_directive_member_suggest)
9397 << Ident << DC << DroppedSpecifier << SS.getRange(),
9398 S.PDiag(diag::note_namespace_defined_here));
9399 } else {
9400 S.diagnoseTypo(Corrected,
9401 S.PDiag(diag::err_using_directive_suggest) << Ident,
9402 S.PDiag(diag::note_namespace_defined_here));
9403 }
9404 R.addDecl(Corrected.getFoundDecl());
9405 return true;
9406 }
9407 return false;
9408}
9409
9410Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9411 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9412 SourceLocation IdentLoc,
9413 IdentifierInfo *NamespcName,
9414 const ParsedAttributesView &AttrList) {
9415 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9416 assert(NamespcName && "Invalid NamespcName.");
9417 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9418
9419 // This can only happen along a recovery path.
9420 while (S->isTemplateParamScope())
9421 S = S->getParent();
9422 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9423
9424 UsingDirectiveDecl *UDir = nullptr;
9425 NestedNameSpecifier *Qualifier = nullptr;
9426 if (SS.isSet())
9427 Qualifier = SS.getScopeRep();
9428
9429 // Lookup namespace name.
9430 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9431 LookupParsedName(R, S, &SS);
9432 if (R.isAmbiguous())
9433 return nullptr;
9434
9435 if (R.empty()) {
9436 R.clear();
9437 // Allow "using namespace std;" or "using namespace ::std;" even if
9438 // "std" hasn't been defined yet, for GCC compatibility.
9439 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9440 NamespcName->isStr("std")) {
9441 Diag(IdentLoc, diag::ext_using_undefined_std);
9442 R.addDecl(getOrCreateStdNamespace());
9443 R.resolveKind();
9444 }
9445 // Otherwise, attempt typo correction.
9446 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9447 }
9448
9449 if (!R.empty()) {
9450 NamedDecl *Named = R.getRepresentativeDecl();
9451 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9452 assert(NS && "expected namespace decl");
9453
9454 // The use of a nested name specifier may trigger deprecation warnings.
9455 DiagnoseUseOfDecl(Named, IdentLoc);
9456
9457 // C++ [namespace.udir]p1:
9458 // A using-directive specifies that the names in the nominated
9459 // namespace can be used in the scope in which the
9460 // using-directive appears after the using-directive. During
9461 // unqualified name lookup (3.4.1), the names appear as if they
9462 // were declared in the nearest enclosing namespace which
9463 // contains both the using-directive and the nominated
9464 // namespace. [Note: in this context, "contains" means "contains
9465 // directly or indirectly". ]
9466
9467 // Find enclosing context containing both using-directive and
9468 // nominated namespace.
9469 DeclContext *CommonAncestor = NS;
9470 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9471 CommonAncestor = CommonAncestor->getParent();
9472
9473 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9474 SS.getWithLocInContext(Context),
9475 IdentLoc, Named, CommonAncestor);
9476
9477 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9478 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9479 Diag(IdentLoc, diag::warn_using_directive_in_header);
9480 }
9481
9482 PushUsingDirective(S, UDir);
9483 } else {
9484 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9485 }
9486
9487 if (UDir)
9488 ProcessDeclAttributeList(S, UDir, AttrList);
9489
9490 return UDir;
9491}
9492
9493void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9494 // If the scope has an associated entity and the using directive is at
9495 // namespace or translation unit scope, add the UsingDirectiveDecl into
9496 // its lookup structure so qualified name lookup can find it.
9497 DeclContext *Ctx = S->getEntity();
9498 if (Ctx && !Ctx->isFunctionOrMethod())
9499 Ctx->addDecl(UDir);
9500 else
9501 // Otherwise, it is at block scope. The using-directives will affect lookup
9502 // only to the end of the scope.
9503 S->PushUsingDirective(UDir);
9504}
9505
9506Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9507 SourceLocation UsingLoc,
9508 SourceLocation TypenameLoc, CXXScopeSpec &SS,
9509 UnqualifiedId &Name,
9510 SourceLocation EllipsisLoc,
9511 const ParsedAttributesView &AttrList) {
9512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9513
9514 if (SS.isEmpty()) {
9515 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9516 return nullptr;
9517 }
9518
9519 switch (Name.getKind()) {
9520 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9521 case UnqualifiedIdKind::IK_Identifier:
9522 case UnqualifiedIdKind::IK_OperatorFunctionId:
9523 case UnqualifiedIdKind::IK_LiteralOperatorId:
9524 case UnqualifiedIdKind::IK_ConversionFunctionId:
9525 break;
9526
9527 case UnqualifiedIdKind::IK_ConstructorName:
9528 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9529 // C++11 inheriting constructors.
9530 Diag(Name.getBeginLoc(),
9531 getLangOpts().CPlusPlus11
9532 ? diag::warn_cxx98_compat_using_decl_constructor
9533 : diag::err_using_decl_constructor)
9534 << SS.getRange();
9535
9536 if (getLangOpts().CPlusPlus11) break;
9537
9538 return nullptr;
9539
9540 case UnqualifiedIdKind::IK_DestructorName:
9541 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9542 return nullptr;
9543
9544 case UnqualifiedIdKind::IK_TemplateId:
9545 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9546 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9547 return nullptr;
9548
9549 case UnqualifiedIdKind::IK_DeductionGuideName:
9550 llvm_unreachable("cannot parse qualified deduction guide name");
9551 }
9552
9553 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9554 DeclarationName TargetName = TargetNameInfo.getName();
9555 if (!TargetName)
9556 return nullptr;
9557
9558 // Warn about access declarations.
9559 if (UsingLoc.isInvalid()) {
9560 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9561 ? diag::err_access_decl
9562 : diag::warn_access_decl_deprecated)
9563 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9564 }
9565
9566 if (EllipsisLoc.isInvalid()) {
9567 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9568 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9569 return nullptr;
9570 } else {
9571 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9572 !TargetNameInfo.containsUnexpandedParameterPack()) {
9573 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9574 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9575 EllipsisLoc = SourceLocation();
9576 }
9577 }
9578
9579 NamedDecl *UD =
9580 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9581 SS, TargetNameInfo, EllipsisLoc, AttrList,
9582 /*IsInstantiation*/false);
9583 if (UD)
9584 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9585
9586 return UD;
9587}
9588
9589/// Determine whether a using declaration considers the given
9590/// declarations as "equivalent", e.g., if they are redeclarations of
9591/// the same entity or are both typedefs of the same type.
9592static bool
9593IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9594 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9595 return true;
9596
9597 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9598 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9599 return Context.hasSameType(TD1->getUnderlyingType(),
9600 TD2->getUnderlyingType());
9601
9602 return false;
9603}
9604
9605
9606/// Determines whether to create a using shadow decl for a particular
9607/// decl, given the set of decls existing prior to this using lookup.
9608bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9609 const LookupResult &Previous,
9610 UsingShadowDecl *&PrevShadow) {
9611 // Diagnose finding a decl which is not from a base class of the
9612 // current class. We do this now because there are cases where this
9613 // function will silently decide not to build a shadow decl, which
9614 // will pre-empt further diagnostics.
9615 //
9616 // We don't need to do this in C++11 because we do the check once on
9617 // the qualifier.
9618 //
9619 // FIXME: diagnose the following if we care enough:
9620 // struct A { int foo; };
9621 // struct B : A { using A::foo; };
9622 // template <class T> struct C : A {};
9623 // template <class T> struct D : C<T> { using B::foo; } // <---
9624 // This is invalid (during instantiation) in C++03 because B::foo
9625 // resolves to the using decl in B, which is not a base class of D<T>.
9626 // We can't diagnose it immediately because C<T> is an unknown
9627 // specialization. The UsingShadowDecl in D<T> then points directly
9628 // to A::foo, which will look well-formed when we instantiate.
9629 // The right solution is to not collapse the shadow-decl chain.
9630 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9631 DeclContext *OrigDC = Orig->getDeclContext();
9632
9633 // Handle enums and anonymous structs.
9634 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9635 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9636 while (OrigRec->isAnonymousStructOrUnion())
9637 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9638
9639 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9640 if (OrigDC == CurContext) {
9641 Diag(Using->getLocation(),
9642 diag::err_using_decl_nested_name_specifier_is_current_class)
9643 << Using->getQualifierLoc().getSourceRange();
9644 Diag(Orig->getLocation(), diag::note_using_decl_target);
9645 Using->setInvalidDecl();
9646 return true;
9647 }
9648
9649 Diag(Using->getQualifierLoc().getBeginLoc(),
9650 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9651 << Using->getQualifier()
9652 << cast<CXXRecordDecl>(CurContext)
9653 << Using->getQualifierLoc().getSourceRange();
9654 Diag(Orig->getLocation(), diag::note_using_decl_target);
9655 Using->setInvalidDecl();
9656 return true;
9657 }
9658 }
9659
9660 if (Previous.empty()) return false;
9661
9662 NamedDecl *Target = Orig;
9663 if (isa<UsingShadowDecl>(Target))
9664 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9665
9666 // If the target happens to be one of the previous declarations, we
9667 // don't have a conflict.
9668 //
9669 // FIXME: but we might be increasing its access, in which case we
9670 // should redeclare it.
9671 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9672 bool FoundEquivalentDecl = false;
9673 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9674 I != E; ++I) {
9675 NamedDecl *D = (*I)->getUnderlyingDecl();
9676 // We can have UsingDecls in our Previous results because we use the same
9677 // LookupResult for checking whether the UsingDecl itself is a valid
9678 // redeclaration.
9679 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9680 continue;
9681
9682 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9683 // C++ [class.mem]p19:
9684 // If T is the name of a class, then [every named member other than
9685 // a non-static data member] shall have a name different from T
9686 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9687 !isa<IndirectFieldDecl>(Target) &&
9688 !isa<UnresolvedUsingValueDecl>(Target) &&
9689 DiagnoseClassNameShadow(
9690 CurContext,
9691 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9692 return true;
9693 }
9694
9695 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9696 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9697 PrevShadow = Shadow;
9698 FoundEquivalentDecl = true;
9699 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9700 // We don't conflict with an existing using shadow decl of an equivalent
9701 // declaration, but we're not a redeclaration of it.
9702 FoundEquivalentDecl = true;
9703 }
9704
9705 if (isVisible(D))
9706 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9707 }
9708
9709 if (FoundEquivalentDecl)
9710 return false;
9711
9712 if (FunctionDecl *FD = Target->getAsFunction()) {
9713 NamedDecl *OldDecl = nullptr;
9714 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9715 /*IsForUsingDecl*/ true)) {
9716 case Ovl_Overload:
9717 return false;
9718
9719 case Ovl_NonFunction:
9720 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9721 break;
9722
9723 // We found a decl with the exact signature.
9724 case Ovl_Match:
9725 // If we're in a record, we want to hide the target, so we
9726 // return true (without a diagnostic) to tell the caller not to
9727 // build a shadow decl.
9728 if (CurContext->isRecord())
9729 return true;
9730
9731 // If we're not in a record, this is an error.
9732 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9733 break;
9734 }
9735
9736 Diag(Target->getLocation(), diag::note_using_decl_target);
9737 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9738 Using->setInvalidDecl();
9739 return true;
9740 }
9741
9742 // Target is not a function.
9743
9744 if (isa<TagDecl>(Target)) {
9745 // No conflict between a tag and a non-tag.
9746 if (!Tag) return false;
9747
9748 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9749 Diag(Target->getLocation(), diag::note_using_decl_target);
9750 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9751 Using->setInvalidDecl();
9752 return true;
9753 }
9754
9755 // No conflict between a tag and a non-tag.
9756 if (!NonTag) return false;
9757
9758 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9759 Diag(Target->getLocation(), diag::note_using_decl_target);
9760 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9761 Using->setInvalidDecl();
9762 return true;
9763}
9764
9765/// Determine whether a direct base class is a virtual base class.
9766static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9767 if (!Derived->getNumVBases())
9768 return false;
9769 for (auto &B : Derived->bases())
9770 if (B.getType()->getAsCXXRecordDecl() == Base)
9771 return B.isVirtual();
9772 llvm_unreachable("not a direct base class");
9773}
9774
9775/// Builds a shadow declaration corresponding to a 'using' declaration.
9776UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9777 UsingDecl *UD,
9778 NamedDecl *Orig,
9779 UsingShadowDecl *PrevDecl) {
9780 // If we resolved to another shadow declaration, just coalesce them.
9781 NamedDecl *Target = Orig;
9782 if (isa<UsingShadowDecl>(Target)) {
9783 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9784 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9785 }
9786
9787 NamedDecl *NonTemplateTarget = Target;
9788 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9789 NonTemplateTarget = TargetTD->getTemplatedDecl();
9790
9791 UsingShadowDecl *Shadow;
9792 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9793 bool IsVirtualBase =
9794 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9795 UD->getQualifier()->getAsRecordDecl());
9796 Shadow = ConstructorUsingShadowDecl::Create(
9797 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9798 } else {
9799 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9800 Target);
9801 }
9802 UD->addShadowDecl(Shadow);
9803
9804 Shadow->setAccess(UD->getAccess());
9805 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9806 Shadow->setInvalidDecl();
9807
9808 Shadow->setPreviousDecl(PrevDecl);
9809
9810 if (S)
9811 PushOnScopeChains(Shadow, S);
9812 else
9813 CurContext->addDecl(Shadow);
9814
9815
9816 return Shadow;
9817}
9818
9819/// Hides a using shadow declaration. This is required by the current
9820/// using-decl implementation when a resolvable using declaration in a
9821/// class is followed by a declaration which would hide or override
9822/// one or more of the using decl's targets; for example:
9823///
9824/// struct Base { void foo(int); };
9825/// struct Derived : Base {
9826/// using Base::foo;
9827/// void foo(int);
9828/// };
9829///
9830/// The governing language is C++03 [namespace.udecl]p12:
9831///
9832/// When a using-declaration brings names from a base class into a
9833/// derived class scope, member functions in the derived class
9834/// override and/or hide member functions with the same name and
9835/// parameter types in a base class (rather than conflicting).
9836///
9837/// There are two ways to implement this:
9838/// (1) optimistically create shadow decls when they're not hidden
9839/// by existing declarations, or
9840/// (2) don't create any shadow decls (or at least don't make them
9841/// visible) until we've fully parsed/instantiated the class.
9842/// The problem with (1) is that we might have to retroactively remove
9843/// a shadow decl, which requires several O(n) operations because the
9844/// decl structures are (very reasonably) not designed for removal.
9845/// (2) avoids this but is very fiddly and phase-dependent.
9846void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9847 if (Shadow->getDeclName().getNameKind() ==
9848 DeclarationName::CXXConversionFunctionName)
9849 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9850
9851 // Remove it from the DeclContext...
9852 Shadow->getDeclContext()->removeDecl(Shadow);
9853
9854 // ...and the scope, if applicable...
9855 if (S) {
9856 S->RemoveDecl(Shadow);
9857 IdResolver.RemoveDecl(Shadow);
9858 }
9859
9860 // ...and the using decl.
9861 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9862
9863 // TODO: complain somehow if Shadow was used. It shouldn't
9864 // be possible for this to happen, because...?
9865}
9866
9867/// Find the base specifier for a base class with the given type.
9868static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9869 QualType DesiredBase,
9870 bool &AnyDependentBases) {
9871 // Check whether the named type is a direct base class.
9872 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9873 for (auto &Base : Derived->bases()) {
9874 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9875 if (CanonicalDesiredBase == BaseType)
9876 return &Base;
9877 if (BaseType->isDependentType())
9878 AnyDependentBases = true;
9879 }
9880 return nullptr;
9881}
9882
9883namespace {
9884class UsingValidatorCCC final : public CorrectionCandidateCallback {
9885public:
9886 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9887 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9888 : HasTypenameKeyword(HasTypenameKeyword),
9889 IsInstantiation(IsInstantiation), OldNNS(NNS),
9890 RequireMemberOf(RequireMemberOf) {}
9891
9892 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9893 NamedDecl *ND = Candidate.getCorrectionDecl();
9894
9895 // Keywords are not valid here.
9896 if (!ND || isa<NamespaceDecl>(ND))
9897 return false;
9898
9899 // Completely unqualified names are invalid for a 'using' declaration.
9900 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9901 return false;
9902
9903 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9904 // reject.
9905
9906 if (RequireMemberOf) {
9907 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9908 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9909 // No-one ever wants a using-declaration to name an injected-class-name
9910 // of a base class, unless they're declaring an inheriting constructor.
9911 ASTContext &Ctx = ND->getASTContext();
9912 if (!Ctx.getLangOpts().CPlusPlus11)
9913 return false;
9914 QualType FoundType = Ctx.getRecordType(FoundRecord);
9915
9916 // Check that the injected-class-name is named as a member of its own
9917 // type; we don't want to suggest 'using Derived::Base;', since that
9918 // means something else.
9919 NestedNameSpecifier *Specifier =
9920 Candidate.WillReplaceSpecifier()
9921 ? Candidate.getCorrectionSpecifier()
9922 : OldNNS;
9923 if (!Specifier->getAsType() ||
9924 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9925 return false;
9926
9927 // Check that this inheriting constructor declaration actually names a
9928 // direct base class of the current class.
9929 bool AnyDependentBases = false;
9930 if (!findDirectBaseWithType(RequireMemberOf,
9931 Ctx.getRecordType(FoundRecord),
9932 AnyDependentBases) &&
9933 !AnyDependentBases)
9934 return false;
9935 } else {
9936 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9937 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9938 return false;
9939
9940 // FIXME: Check that the base class member is accessible?
9941 }
9942 } else {
9943 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9944 if (FoundRecord && FoundRecord->isInjectedClassName())
9945 return false;
9946 }
9947
9948 if (isa<TypeDecl>(ND))
9949 return HasTypenameKeyword || !IsInstantiation;
9950
9951 return !HasTypenameKeyword;
9952 }
9953
9954 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9955 return llvm::make_unique<UsingValidatorCCC>(*this);
9956 }
9957
9958private:
9959 bool HasTypenameKeyword;
9960 bool IsInstantiation;
9961 NestedNameSpecifier *OldNNS;
9962 CXXRecordDecl *RequireMemberOf;
9963};
9964} // end anonymous namespace
9965
9966/// Builds a using declaration.
9967///
9968/// \param IsInstantiation - Whether this call arises from an
9969/// instantiation of an unresolved using declaration. We treat
9970/// the lookup differently for these declarations.
9971NamedDecl *Sema::BuildUsingDeclaration(
9972 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9973 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9974 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9975 const ParsedAttributesView &AttrList, bool IsInstantiation) {
9976 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9977 SourceLocation IdentLoc = NameInfo.getLoc();
9978 assert(IdentLoc.isValid() && "Invalid TargetName location.");
9979
9980 // FIXME: We ignore attributes for now.
9981
9982 // For an inheriting constructor declaration, the name of the using
9983 // declaration is the name of a constructor in this class, not in the
9984 // base class.
9985 DeclarationNameInfo UsingName = NameInfo;
9986 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9987 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9988 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9989 Context.getCanonicalType(Context.getRecordType(RD))));
9990
9991 // Do the redeclaration lookup in the current scope.
9992 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9993 ForVisibleRedeclaration);
9994 Previous.setHideTags(false);
9995 if (S) {
9996 LookupName(Previous, S);
9997
9998 // It is really dumb that we have to do this.
9999 LookupResult::Filter F = Previous.makeFilter();
10000 while (F.hasNext()) {
10001 NamedDecl *D = F.next();
10002 if (!isDeclInScope(D, CurContext, S))
10003 F.erase();
10004 // If we found a local extern declaration that's not ordinarily visible,
10005 // and this declaration is being added to a non-block scope, ignore it.
10006 // We're only checking for scope conflicts here, not also for violations
10007 // of the linkage rules.
10008 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10009 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10010 F.erase();
10011 }
10012 F.done();
10013 } else {
10014 assert(IsInstantiation && "no scope in non-instantiation");
10015 if (CurContext->isRecord())
10016 LookupQualifiedName(Previous, CurContext);
10017 else {
10018 // No redeclaration check is needed here; in non-member contexts we
10019 // diagnosed all possible conflicts with other using-declarations when
10020 // building the template:
10021 //
10022 // For a dependent non-type using declaration, the only valid case is
10023 // if we instantiate to a single enumerator. We check for conflicts
10024 // between shadow declarations we introduce, and we check in the template
10025 // definition for conflicts between a non-type using declaration and any
10026 // other declaration, which together covers all cases.
10027 //
10028 // A dependent typename using declaration will never successfully
10029 // instantiate, since it will always name a class member, so we reject
10030 // that in the template definition.
10031 }
10032 }
10033
10034 // Check for invalid redeclarations.
10035 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10036 SS, IdentLoc, Previous))
10037 return nullptr;
10038
10039 // Check for bad qualifiers.
10040 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10041 IdentLoc))
10042 return nullptr;
10043
10044 DeclContext *LookupContext = computeDeclContext(SS);
10045 NamedDecl *D;
10046 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10047 if (!LookupContext || EllipsisLoc.isValid()) {
10048 if (HasTypenameKeyword) {
10049 // FIXME: not all declaration name kinds are legal here
10050 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10051 UsingLoc, TypenameLoc,
10052 QualifierLoc,
10053 IdentLoc, NameInfo.getName(),
10054 EllipsisLoc);
10055 } else {
10056 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10057 QualifierLoc, NameInfo, EllipsisLoc);
10058 }
10059 D->setAccess(AS);
10060 CurContext->addDecl(D);
10061 return D;
10062 }
10063
10064 auto Build = [&](bool Invalid) {
10065 UsingDecl *UD =
10066 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10067 UsingName, HasTypenameKeyword);
10068 UD->setAccess(AS);
10069 CurContext->addDecl(UD);
10070 UD->setInvalidDecl(Invalid);
10071 return UD;
10072 };
10073 auto BuildInvalid = [&]{ return Build(true); };
10074 auto BuildValid = [&]{ return Build(false); };
10075
10076 if (RequireCompleteDeclContext(SS, LookupContext))
10077 return BuildInvalid();
10078
10079 // Look up the target name.
10080 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10081
10082 // Unlike most lookups, we don't always want to hide tag
10083 // declarations: tag names are visible through the using declaration
10084 // even if hidden by ordinary names, *except* in a dependent context
10085 // where it's important for the sanity of two-phase lookup.
10086 if (!IsInstantiation)
10087 R.setHideTags(false);
10088
10089 // For the purposes of this lookup, we have a base object type
10090 // equal to that of the current context.
10091 if (CurContext->isRecord()) {
10092 R.setBaseObjectType(
10093 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10094 }
10095
10096 LookupQualifiedName(R, LookupContext);
10097
10098 // Try to correct typos if possible. If constructor name lookup finds no
10099 // results, that means the named class has no explicit constructors, and we
10100 // suppressed declaring implicit ones (probably because it's dependent or
10101 // invalid).
10102 if (R.empty() &&
10103 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10104 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10105 // it will believe that glibc provides a ::gets in cases where it does not,
10106 // and will try to pull it into namespace std with a using-declaration.
10107 // Just ignore the using-declaration in that case.
10108 auto *II = NameInfo.getName().getAsIdentifierInfo();
10109 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10110 CurContext->isStdNamespace() &&
10111 isa<TranslationUnitDecl>(LookupContext) &&
10112 getSourceManager().isInSystemHeader(UsingLoc))
10113 return nullptr;
10114 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10115 dyn_cast<CXXRecordDecl>(CurContext));
10116 if (TypoCorrection Corrected =
10117 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10118 CTK_ErrorRecovery)) {
10119 // We reject candidates where DroppedSpecifier == true, hence the
10120 // literal '0' below.
10121 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10122 << NameInfo.getName() << LookupContext << 0
10123 << SS.getRange());
10124
10125 // If we picked a correction with no attached Decl we can't do anything
10126 // useful with it, bail out.
10127 NamedDecl *ND = Corrected.getCorrectionDecl();
10128 if (!ND)
10129 return BuildInvalid();
10130
10131 // If we corrected to an inheriting constructor, handle it as one.
10132 auto *RD = dyn_cast<CXXRecordDecl>(ND);
10133 if (RD && RD->isInjectedClassName()) {
10134 // The parent of the injected class name is the class itself.
10135 RD = cast<CXXRecordDecl>(RD->getParent());
10136
10137 // Fix up the information we'll use to build the using declaration.
10138 if (Corrected.WillReplaceSpecifier()) {
10139 NestedNameSpecifierLocBuilder Builder;
10140 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10141 QualifierLoc.getSourceRange());
10142 QualifierLoc = Builder.getWithLocInContext(Context);
10143 }
10144
10145 // In this case, the name we introduce is the name of a derived class
10146 // constructor.
10147 auto *CurClass = cast<CXXRecordDecl>(CurContext);
10148 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10149 Context.getCanonicalType(Context.getRecordType(CurClass))));
10150 UsingName.setNamedTypeInfo(nullptr);
10151 for (auto *Ctor : LookupConstructors(RD))
10152 R.addDecl(Ctor);
10153 R.resolveKind();
10154 } else {
10155 // FIXME: Pick up all the declarations if we found an overloaded
10156 // function.
10157 UsingName.setName(ND->getDeclName());
10158 R.addDecl(ND);
10159 }
10160 } else {
10161 Diag(IdentLoc, diag::err_no_member)
10162 << NameInfo.getName() << LookupContext << SS.getRange();
10163 return BuildInvalid();
10164 }
10165 }
10166
10167 if (R.isAmbiguous())
10168 return BuildInvalid();
10169
10170 if (HasTypenameKeyword) {
10171 // If we asked for a typename and got a non-type decl, error out.
10172 if (!R.getAsSingle<TypeDecl>()) {
10173 Diag(IdentLoc, diag::err_using_typename_non_type);
10174 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10175 Diag((*I)->getUnderlyingDecl()->getLocation(),
10176 diag::note_using_decl_target);
10177 return BuildInvalid();
10178 }
10179 } else {
10180 // If we asked for a non-typename and we got a type, error out,
10181 // but only if this is an instantiation of an unresolved using
10182 // decl. Otherwise just silently find the type name.
10183 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10184 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10185 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10186 return BuildInvalid();
10187 }
10188 }
10189
10190 // C++14 [namespace.udecl]p6:
10191 // A using-declaration shall not name a namespace.
10192 if (R.getAsSingle<NamespaceDecl>()) {
10193 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10194 << SS.getRange();
10195 return BuildInvalid();
10196 }
10197
10198 // C++14 [namespace.udecl]p7:
10199 // A using-declaration shall not name a scoped enumerator.
10200 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10201 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10202 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10203 << SS.getRange();
10204 return BuildInvalid();
10205 }
10206 }
10207
10208 UsingDecl *UD = BuildValid();
10209
10210 // Some additional rules apply to inheriting constructors.
10211 if (UsingName.getName().getNameKind() ==
10212 DeclarationName::CXXConstructorName) {
10213 // Suppress access diagnostics; the access check is instead performed at the
10214 // point of use for an inheriting constructor.
10215 R.suppressDiagnostics();
10216 if (CheckInheritingConstructorUsingDecl(UD))
10217 return UD;
10218 }
10219
10220 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10221 UsingShadowDecl *PrevDecl = nullptr;
10222 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10223 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10224 }
10225
10226 return UD;
10227}
10228
10229NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10230 ArrayRef<NamedDecl *> Expansions) {
10231 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10232 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10233 isa<UsingPackDecl>(InstantiatedFrom));
10234
10235 auto *UPD =
10236 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10237 UPD->setAccess(InstantiatedFrom->getAccess());
10238 CurContext->addDecl(UPD);
10239 return UPD;
10240}
10241
10242/// Additional checks for a using declaration referring to a constructor name.
10243bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10244 assert(!UD->hasTypename() && "expecting a constructor name");
10245
10246 const Type *SourceType = UD->getQualifier()->getAsType();
10247 assert(SourceType &&
10248 "Using decl naming constructor doesn't have type in scope spec.");
10249 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10250
10251 // Check whether the named type is a direct base class.
10252 bool AnyDependentBases = false;
10253 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10254 AnyDependentBases);
10255 if (!Base && !AnyDependentBases) {
10256 Diag(UD->getUsingLoc(),
10257 diag::err_using_decl_constructor_not_in_direct_base)
10258 << UD->getNameInfo().getSourceRange()
10259 << QualType(SourceType, 0) << TargetClass;
10260 UD->setInvalidDecl();
10261 return true;
10262 }
10263
10264 if (Base)
10265 Base->setInheritConstructors();
10266
10267 return false;
10268}
10269
10270/// Checks that the given using declaration is not an invalid
10271/// redeclaration. Note that this is checking only for the using decl
10272/// itself, not for any ill-formedness among the UsingShadowDecls.
10273bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10274 bool HasTypenameKeyword,
10275 const CXXScopeSpec &SS,
10276 SourceLocation NameLoc,
10277 const LookupResult &Prev) {
10278 NestedNameSpecifier *Qual = SS.getScopeRep();
10279
10280 // C++03 [namespace.udecl]p8:
10281 // C++0x [namespace.udecl]p10:
10282 // A using-declaration is a declaration and can therefore be used
10283 // repeatedly where (and only where) multiple declarations are
10284 // allowed.
10285 //
10286 // That's in non-member contexts.
10287 if (!CurContext->getRedeclContext()->isRecord()) {
10288 // A dependent qualifier outside a class can only ever resolve to an
10289 // enumeration type. Therefore it conflicts with any other non-type
10290 // declaration in the same scope.
10291 // FIXME: How should we check for dependent type-type conflicts at block
10292 // scope?
10293 if (Qual->isDependent() && !HasTypenameKeyword) {
10294 for (auto *D : Prev) {
10295 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10296 bool OldCouldBeEnumerator =
10297 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10298 Diag(NameLoc,
10299 OldCouldBeEnumerator ? diag::err_redefinition
10300 : diag::err_redefinition_different_kind)
10301 << Prev.getLookupName();
10302 Diag(D->getLocation(), diag::note_previous_definition);
10303 return true;
10304 }
10305 }
10306 }
10307 return false;
10308 }
10309
10310 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10311 NamedDecl *D = *I;
10312
10313 bool DTypename;
10314 NestedNameSpecifier *DQual;
10315 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10316 DTypename = UD->hasTypename();
10317 DQual = UD->getQualifier();
10318 } else if (UnresolvedUsingValueDecl *UD
10319 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10320 DTypename = false;
10321 DQual = UD->getQualifier();
10322 } else if (UnresolvedUsingTypenameDecl *UD
10323 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10324 DTypename = true;
10325 DQual = UD->getQualifier();
10326 } else continue;
10327
10328 // using decls differ if one says 'typename' and the other doesn't.
10329 // FIXME: non-dependent using decls?
10330 if (HasTypenameKeyword != DTypename) continue;
10331
10332 // using decls differ if they name different scopes (but note that
10333 // template instantiation can cause this check to trigger when it
10334 // didn't before instantiation).
10335 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10336 Context.getCanonicalNestedNameSpecifier(DQual))
10337 continue;
10338
10339 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10340 Diag(D->getLocation(), diag::note_using_decl) << 1;
10341 return true;
10342 }
10343
10344 return false;
10345}
10346
10347
10348/// Checks that the given nested-name qualifier used in a using decl
10349/// in the current context is appropriately related to the current
10350/// scope. If an error is found, diagnoses it and returns true.
10351bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10352 bool HasTypename,
10353 const CXXScopeSpec &SS,
10354 const DeclarationNameInfo &NameInfo,
10355 SourceLocation NameLoc) {
10356 DeclContext *NamedContext = computeDeclContext(SS);
10357
10358 if (!CurContext->isRecord()) {
10359 // C++03 [namespace.udecl]p3:
10360 // C++0x [namespace.udecl]p8:
10361 // A using-declaration for a class member shall be a member-declaration.
10362
10363 // If we weren't able to compute a valid scope, it might validly be a
10364 // dependent class scope or a dependent enumeration unscoped scope. If
10365 // we have a 'typename' keyword, the scope must resolve to a class type.
10366 if ((HasTypename && !NamedContext) ||
10367 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10368 auto *RD = NamedContext
10369 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10370 : nullptr;
10371 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10372 RD = nullptr;
10373
10374 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10375 << SS.getRange();
10376
10377 // If we have a complete, non-dependent source type, try to suggest a
10378 // way to get the same effect.
10379 if (!RD)
10380 return true;
10381
10382 // Find what this using-declaration was referring to.
10383 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10384 R.setHideTags(false);
10385 R.suppressDiagnostics();
10386 LookupQualifiedName(R, RD);
10387
10388 if (R.getAsSingle<TypeDecl>()) {
10389 if (getLangOpts().CPlusPlus11) {
10390 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10391 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10392 << 0 // alias declaration
10393 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10394 NameInfo.getName().getAsString() +
10395 " = ");
10396 } else {
10397 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10398 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10399 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10400 << 1 // typedef declaration
10401 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10402 << FixItHint::CreateInsertion(
10403 InsertLoc, " " + NameInfo.getName().getAsString());
10404 }
10405 } else if (R.getAsSingle<VarDecl>()) {
10406 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10407 // repeating the type of the static data member here.
10408 FixItHint FixIt;
10409 if (getLangOpts().CPlusPlus11) {
10410 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10411 FixIt = FixItHint::CreateReplacement(
10412 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10413 }
10414
10415 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10416 << 2 // reference declaration
10417 << FixIt;
10418 } else if (R.getAsSingle<EnumConstantDecl>()) {
10419 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10420 // repeating the type of the enumeration here, and we can't do so if
10421 // the type is anonymous.
10422 FixItHint FixIt;
10423 if (getLangOpts().CPlusPlus11) {
10424 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10425 FixIt = FixItHint::CreateReplacement(
10426 UsingLoc,
10427 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10428 }
10429
10430 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10431 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10432 << FixIt;
10433 }
10434 return true;
10435 }
10436
10437 // Otherwise, this might be valid.
10438 return false;
10439 }
10440
10441 // The current scope is a record.
10442
10443 // If the named context is dependent, we can't decide much.
10444 if (!NamedContext) {
10445 // FIXME: in C++0x, we can diagnose if we can prove that the
10446 // nested-name-specifier does not refer to a base class, which is
10447 // still possible in some cases.
10448
10449 // Otherwise we have to conservatively report that things might be
10450 // okay.
10451 return false;
10452 }
10453
10454 if (!NamedContext->isRecord()) {
10455 // Ideally this would point at the last name in the specifier,
10456 // but we don't have that level of source info.
10457 Diag(SS.getRange().getBegin(),
10458 diag::err_using_decl_nested_name_specifier_is_not_class)
10459 << SS.getScopeRep() << SS.getRange();
10460 return true;
10461 }
10462
10463 if (!NamedContext->isDependentContext() &&
10464 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10465 return true;
10466
10467 if (getLangOpts().CPlusPlus11) {
10468 // C++11 [namespace.udecl]p3:
10469 // In a using-declaration used as a member-declaration, the
10470 // nested-name-specifier shall name a base class of the class
10471 // being defined.
10472
10473 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10474 cast<CXXRecordDecl>(NamedContext))) {
10475 if (CurContext == NamedContext) {
10476 Diag(NameLoc,
10477 diag::err_using_decl_nested_name_specifier_is_current_class)
10478 << SS.getRange();
10479 return true;
10480 }
10481
10482 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10483 Diag(SS.getRange().getBegin(),
10484 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10485 << SS.getScopeRep()
10486 << cast<CXXRecordDecl>(CurContext)
10487 << SS.getRange();
10488 }
10489 return true;
10490 }
10491
10492 return false;
10493 }
10494
10495 // C++03 [namespace.udecl]p4:
10496 // A using-declaration used as a member-declaration shall refer
10497 // to a member of a base class of the class being defined [etc.].
10498
10499 // Salient point: SS doesn't have to name a base class as long as
10500 // lookup only finds members from base classes. Therefore we can
10501 // diagnose here only if we can prove that that can't happen,
10502 // i.e. if the class hierarchies provably don't intersect.
10503
10504 // TODO: it would be nice if "definitely valid" results were cached
10505 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10506 // need to be repeated.
10507
10508 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10509 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10510 Bases.insert(Base);
10511 return true;
10512 };
10513
10514 // Collect all bases. Return false if we find a dependent base.
10515 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10516 return false;
10517
10518 // Returns true if the base is dependent or is one of the accumulated base
10519 // classes.
10520 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10521 return !Bases.count(Base);
10522 };
10523
10524 // Return false if the class has a dependent base or if it or one
10525 // of its bases is present in the base set of the current context.
10526 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10527 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10528 return false;
10529
10530 Diag(SS.getRange().getBegin(),
10531 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10532 << SS.getScopeRep()
10533 << cast<CXXRecordDecl>(CurContext)
10534 << SS.getRange();
10535
10536 return true;
10537}
10538
10539Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10540 MultiTemplateParamsArg TemplateParamLists,
10541 SourceLocation UsingLoc, UnqualifiedId &Name,
10542 const ParsedAttributesView &AttrList,
10543 TypeResult Type, Decl *DeclFromDeclSpec) {
10544 // Skip up to the relevant declaration scope.
10545 while (S->isTemplateParamScope())
10546 S = S->getParent();
10547 assert((S->getFlags() & Scope::DeclScope) &&
10548 "got alias-declaration outside of declaration scope");
10549
10550 if (Type.isInvalid())
10551 return nullptr;
10552
10553 bool Invalid = false;
10554 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10555 TypeSourceInfo *TInfo = nullptr;
10556 GetTypeFromParser(Type.get(), &TInfo);
10557
10558 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10559 return nullptr;
10560
10561 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10562 UPPC_DeclarationType)) {
10563 Invalid = true;
10564 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10565 TInfo->getTypeLoc().getBeginLoc());
10566 }
10567
10568 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10569 TemplateParamLists.size()
10570 ? forRedeclarationInCurContext()
10571 : ForVisibleRedeclaration);
10572 LookupName(Previous, S);
10573
10574 // Warn about shadowing the name of a template parameter.
10575 if (Previous.isSingleResult() &&
10576 Previous.getFoundDecl()->isTemplateParameter()) {
10577 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10578 Previous.clear();
10579 }
10580
10581 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10582 "name in alias declaration must be an identifier");
10583 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10584 Name.StartLocation,
10585 Name.Identifier, TInfo);
10586
10587 NewTD->setAccess(AS);
10588
10589 if (Invalid)
10590 NewTD->setInvalidDecl();
10591
10592 ProcessDeclAttributeList(S, NewTD, AttrList);
10593 AddPragmaAttributes(S, NewTD);
10594
10595 CheckTypedefForVariablyModifiedType(S, NewTD);
10596 Invalid |= NewTD->isInvalidDecl();
10597
10598 bool Redeclaration = false;
10599
10600 NamedDecl *NewND;
10601 if (TemplateParamLists.size()) {
10602 TypeAliasTemplateDecl *OldDecl = nullptr;
10603 TemplateParameterList *OldTemplateParams = nullptr;
10604
10605 if (TemplateParamLists.size() != 1) {
10606 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10607 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10608 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10609 }
10610 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10611
10612 // Check that we can declare a template here.
10613 if (CheckTemplateDeclScope(S, TemplateParams))
10614 return nullptr;
10615
10616 // Only consider previous declarations in the same scope.
10617 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10618 /*ExplicitInstantiationOrSpecialization*/false);
10619 if (!Previous.empty()) {
10620 Redeclaration = true;
10621
10622 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10623 if (!OldDecl && !Invalid) {
10624 Diag(UsingLoc, diag::err_redefinition_different_kind)
10625 << Name.Identifier;
10626
10627 NamedDecl *OldD = Previous.getRepresentativeDecl();
10628 if (OldD->getLocation().isValid())
10629 Diag(OldD->getLocation(), diag::note_previous_definition);
10630
10631 Invalid = true;
10632 }
10633
10634 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10635 if (TemplateParameterListsAreEqual(TemplateParams,
10636 OldDecl->getTemplateParameters(),
10637 /*Complain=*/true,
10638 TPL_TemplateMatch))
10639 OldTemplateParams =
10640 OldDecl->getMostRecentDecl()->getTemplateParameters();
10641 else
10642 Invalid = true;
10643
10644 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10645 if (!Invalid &&
10646 !Context.hasSameType(OldTD->getUnderlyingType(),
10647 NewTD->getUnderlyingType())) {
10648 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10649 // but we can't reasonably accept it.
10650 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10651 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10652 if (OldTD->getLocation().isValid())
10653 Diag(OldTD->getLocation(), diag::note_previous_definition);
10654 Invalid = true;
10655 }
10656 }
10657 }
10658
10659 // Merge any previous default template arguments into our parameters,
10660 // and check the parameter list.
10661 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10662 TPC_TypeAliasTemplate))
10663 return nullptr;
10664
10665 TypeAliasTemplateDecl *NewDecl =
10666 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10667 Name.Identifier, TemplateParams,
10668 NewTD);
10669 NewTD->setDescribedAliasTemplate(NewDecl);
10670
10671 NewDecl->setAccess(AS);
10672
10673 if (Invalid)
10674 NewDecl->setInvalidDecl();
10675 else if (OldDecl) {
10676 NewDecl->setPreviousDecl(OldDecl);
10677 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10678 }
10679
10680 NewND = NewDecl;
10681 } else {
10682 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10683 setTagNameForLinkagePurposes(TD, NewTD);
10684 handleTagNumbering(TD, S);
10685 }
10686 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10687 NewND = NewTD;
10688 }
10689
10690 PushOnScopeChains(NewND, S);
10691 ActOnDocumentableDecl(NewND);
10692 return NewND;
10693}
10694
10695Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10696 SourceLocation AliasLoc,
10697 IdentifierInfo *Alias, CXXScopeSpec &SS,
10698 SourceLocation IdentLoc,
10699 IdentifierInfo *Ident) {
10700
10701 // Lookup the namespace name.
10702 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10703 LookupParsedName(R, S, &SS);
10704
10705 if (R.isAmbiguous())
10706 return nullptr;
10707
10708 if (R.empty()) {
10709 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10710 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10711 return nullptr;
10712 }
10713 }
10714 assert(!R.isAmbiguous() && !R.empty());
10715 NamedDecl *ND = R.getRepresentativeDecl();
10716
10717 // Check if we have a previous declaration with the same name.
10718 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10719 ForVisibleRedeclaration);
10720 LookupName(PrevR, S);
10721
10722 // Check we're not shadowing a template parameter.
10723 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10724 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10725 PrevR.clear();
10726 }
10727
10728 // Filter out any other lookup result from an enclosing scope.
10729 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10730 /*AllowInlineNamespace*/false);
10731
10732 // Find the previous declaration and check that we can redeclare it.
10733 NamespaceAliasDecl *Prev = nullptr;
10734 if (PrevR.isSingleResult()) {
10735 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10736 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10737 // We already have an alias with the same name that points to the same
10738 // namespace; check that it matches.
10739 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10740 Prev = AD;
10741 } else if (isVisible(PrevDecl)) {
10742 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10743 << Alias;
10744 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10745 << AD->getNamespace();
10746 return nullptr;
10747 }
10748 } else if (isVisible(PrevDecl)) {
10749 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10750 ? diag::err_redefinition
10751 : diag::err_redefinition_different_kind;
10752 Diag(AliasLoc, DiagID) << Alias;
10753 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10754 return nullptr;
10755 }
10756 }
10757
10758 // The use of a nested name specifier may trigger deprecation warnings.
10759 DiagnoseUseOfDecl(ND, IdentLoc);
10760
10761 NamespaceAliasDecl *AliasDecl =
10762 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10763 Alias, SS.getWithLocInContext(Context),
10764 IdentLoc, ND);
10765 if (Prev)
10766 AliasDecl->setPreviousDecl(Prev);
10767
10768 PushOnScopeChains(AliasDecl, S);
10769 return AliasDecl;
10770}
10771
10772namespace {
10773struct SpecialMemberExceptionSpecInfo
10774 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10775 SourceLocation Loc;
10776 Sema::ImplicitExceptionSpecification ExceptSpec;
10777
10778 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10779 Sema::CXXSpecialMember CSM,
10780 Sema::InheritedConstructorInfo *ICI,
10781 SourceLocation Loc)
10782 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10783
10784 bool visitBase(CXXBaseSpecifier *Base);
10785 bool visitField(FieldDecl *FD);
10786
10787 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10788 unsigned Quals);
10789
10790 void visitSubobjectCall(Subobject Subobj,
10791 Sema::SpecialMemberOverloadResult SMOR);
10792};
10793}
10794
10795bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10796 auto *RT = Base->getType()->getAs<RecordType>();
10797 if (!RT)
10798 return false;
10799
10800 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10801 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10802 if (auto *BaseCtor = SMOR.getMethod()) {
10803 visitSubobjectCall(Base, BaseCtor);
10804 return false;
10805 }
10806
10807 visitClassSubobject(BaseClass, Base, 0);
10808 return false;
10809}
10810
10811bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10812 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10813 Expr *E = FD->getInClassInitializer();
10814 if (!E)
10815 // FIXME: It's a little wasteful to build and throw away a
10816 // CXXDefaultInitExpr here.
10817 // FIXME: We should have a single context note pointing at Loc, and
10818 // this location should be MD->getLocation() instead, since that's
10819 // the location where we actually use the default init expression.
10820 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10821 if (E)
10822 ExceptSpec.CalledExpr(E);
10823 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10824 ->getAs<RecordType>()) {
10825 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10826 FD->getType().getCVRQualifiers());
10827 }
10828 return false;
10829}
10830
10831void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10832 Subobject Subobj,
10833 unsigned Quals) {
10834 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10835 bool IsMutable = Field && Field->isMutable();
10836 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10837}
10838
10839void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10840 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10841 // Note, if lookup fails, it doesn't matter what exception specification we
10842 // choose because the special member will be deleted.
10843 if (CXXMethodDecl *MD = SMOR.getMethod())
10844 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10845}
10846
10847namespace {
10848/// RAII object to register a special member as being currently declared.
10849struct ComputingExceptionSpec {
10850 Sema &S;
10851
10852 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10853 : S(S) {
10854 Sema::CodeSynthesisContext Ctx;
10855 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10856 Ctx.PointOfInstantiation = Loc;
10857 Ctx.Entity = MD;
10858 S.pushCodeSynthesisContext(Ctx);
10859 }
10860 ~ComputingExceptionSpec() {
10861 S.popCodeSynthesisContext();
10862 }
10863};
10864}
10865
10866bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10867 llvm::APSInt Result;
10868 ExprResult Converted = CheckConvertedConstantExpression(
10869 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10870 ExplicitSpec.setExpr(Converted.get());
10871 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10872 ExplicitSpec.setKind(Result.getBoolValue()
10873 ? ExplicitSpecKind::ResolvedTrue
10874 : ExplicitSpecKind::ResolvedFalse);
10875 return true;
10876 }
10877 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10878 return false;
10879}
10880
10881ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10882 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10883 if (!ExplicitExpr->isTypeDependent())
10884 tryResolveExplicitSpecifier(ES);
10885 return ES;
10886}
10887
10888static Sema::ImplicitExceptionSpecification
10889ComputeDefaultedSpecialMemberExceptionSpec(
10890 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10891 Sema::InheritedConstructorInfo *ICI) {
10892 ComputingExceptionSpec CES(S, MD, Loc);
10893
10894 CXXRecordDecl *ClassDecl = MD->getParent();
10895
10896 // C++ [except.spec]p14:
10897 // An implicitly declared special member function (Clause 12) shall have an
10898 // exception-specification. [...]
10899 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10900 if (ClassDecl->isInvalidDecl())
10901 return Info.ExceptSpec;
10902
10903 // FIXME: If this diagnostic fires, we're probably missing a check for
10904 // attempting to resolve an exception specification before it's known
10905 // at a higher level.
10906 if (S.RequireCompleteType(MD->getLocation(),
10907 S.Context.getRecordType(ClassDecl),
10908 diag::err_exception_spec_incomplete_type))
10909 return Info.ExceptSpec;
10910
10911 // C++1z [except.spec]p7:
10912 // [Look for exceptions thrown by] a constructor selected [...] to
10913 // initialize a potentially constructed subobject,
10914 // C++1z [except.spec]p8:
10915 // The exception specification for an implicitly-declared destructor, or a
10916 // destructor without a noexcept-specifier, is potentially-throwing if and
10917 // only if any of the destructors for any of its potentially constructed
10918 // subojects is potentially throwing.
10919 // FIXME: We respect the first rule but ignore the "potentially constructed"
10920 // in the second rule to resolve a core issue (no number yet) that would have
10921 // us reject:
10922 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10923 // struct B : A {};
10924 // struct C : B { void f(); };
10925 // ... due to giving B::~B() a non-throwing exception specification.
10926 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10927 : Info.VisitAllBases);
10928
10929 return Info.ExceptSpec;
10930}
10931
10932namespace {
10933/// RAII object to register a special member as being currently declared.
10934struct DeclaringSpecialMember {
10935 Sema &S;
10936 Sema::SpecialMemberDecl D;
10937 Sema::ContextRAII SavedContext;
10938 bool WasAlreadyBeingDeclared;
10939
10940 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10941 : S(S), D(RD, CSM), SavedContext(S, RD) {
10942 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10943 if (WasAlreadyBeingDeclared)
10944 // This almost never happens, but if it does, ensure that our cache
10945 // doesn't contain a stale result.
10946 S.SpecialMemberCache.clear();
10947 else {
10948 // Register a note to be produced if we encounter an error while
10949 // declaring the special member.
10950 Sema::CodeSynthesisContext Ctx;
10951 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10952 // FIXME: We don't have a location to use here. Using the class's
10953 // location maintains the fiction that we declare all special members
10954 // with the class, but (1) it's not clear that lying about that helps our
10955 // users understand what's going on, and (2) there may be outer contexts
10956 // on the stack (some of which are relevant) and printing them exposes
10957 // our lies.
10958 Ctx.PointOfInstantiation = RD->getLocation();
10959 Ctx.Entity = RD;
10960 Ctx.SpecialMember = CSM;
10961 S.pushCodeSynthesisContext(Ctx);
10962 }
10963 }
10964 ~DeclaringSpecialMember() {
10965 if (!WasAlreadyBeingDeclared) {
10966 S.SpecialMembersBeingDeclared.erase(D);
10967 S.popCodeSynthesisContext();
10968 }
10969 }
10970
10971 /// Are we already trying to declare this special member?
10972 bool isAlreadyBeingDeclared() const {
10973 return WasAlreadyBeingDeclared;
10974 }
10975};
10976}
10977
10978void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10979 // Look up any existing declarations, but don't trigger declaration of all
10980 // implicit special members with this name.
10981 DeclarationName Name = FD->getDeclName();
10982 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10983 ForExternalRedeclaration);
10984 for (auto *D : FD->getParent()->lookup(Name))
10985 if (auto *Acceptable = R.getAcceptableDecl(D))
10986 R.addDecl(Acceptable);
10987 R.resolveKind();
10988 R.suppressDiagnostics();
10989
10990 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10991}
10992
10993void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
10994 QualType ResultTy,
10995 ArrayRef<QualType> Args) {
10996 // Build an exception specification pointing back at this constructor.
10997 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
10998
10999 if (getLangOpts().OpenCLCPlusPlus) {
11000 // OpenCL: Implicitly defaulted special member are of the generic address
11001 // space.
11002 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11003 }
11004
11005 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11006 SpecialMem->setType(QT);
11007}
11008
11009CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11010 CXXRecordDecl *ClassDecl) {
11011 // C++ [class.ctor]p5:
11012 // A default constructor for a class X is a constructor of class X
11013 // that can be called without an argument. If there is no
11014 // user-declared constructor for class X, a default constructor is
11015 // implicitly declared. An implicitly-declared default constructor
11016 // is an inline public member of its class.
11017 assert(ClassDecl->needsImplicitDefaultConstructor() &&
11018 "Should not build implicit default constructor!");
11019
11020 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11021 if (DSM.isAlreadyBeingDeclared())
11022 return nullptr;
11023
11024 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11025 CXXDefaultConstructor,
11026 false);
11027
11028 // Create the actual constructor declaration.
11029 CanQualType ClassType
11030 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11031 SourceLocation ClassLoc = ClassDecl->getLocation();
11032 DeclarationName Name
11033 = Context.DeclarationNames.getCXXConstructorName(ClassType);
11034 DeclarationNameInfo NameInfo(Name, ClassLoc);
11035 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11036 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11037 /*TInfo=*/nullptr, ExplicitSpecifier(),
11038 /*isInline=*/true, /*isImplicitlyDeclared=*/true, Constexpr);
11039 DefaultCon->setAccess(AS_public);
11040 DefaultCon->setDefaulted();
11041
11042 if (getLangOpts().CUDA) {
11043 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11044 DefaultCon,
11045 /* ConstRHS */ false,
11046 /* Diagnose */ false);
11047 }
11048
11049 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11050
11051 // We don't need to use SpecialMemberIsTrivial here; triviality for default
11052 // constructors is easy to compute.
11053 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11054
11055 // Note that we have declared this constructor.
11056 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11057
11058 Scope *S = getScopeForContext(ClassDecl);
11059 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11060
11061 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11062 SetDeclDeleted(DefaultCon, ClassLoc);
11063
11064 if (S)
11065 PushOnScopeChains(DefaultCon, S, false);
11066 ClassDecl->addDecl(DefaultCon);
11067
11068 return DefaultCon;
11069}
11070
11071void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11072 CXXConstructorDecl *Constructor) {
11073 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11074 !Constructor->doesThisDeclarationHaveABody() &&
11075 !Constructor->isDeleted()) &&
11076 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11077 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11078 return;
11079
11080 CXXRecordDecl *ClassDecl = Constructor->getParent();
11081 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11082
11083 SynthesizedFunctionScope Scope(*this, Constructor);
11084
11085 // The exception specification is needed because we are defining the
11086 // function.
11087 ResolveExceptionSpec(CurrentLocation,
11088 Constructor->getType()->castAs<FunctionProtoType>());
11089 MarkVTableUsed(CurrentLocation, ClassDecl);
11090
11091 // Add a context note for diagnostics produced after this point.
11092 Scope.addContextNote(CurrentLocation);
11093
11094 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11095 Constructor->setInvalidDecl();
11096 return;
11097 }
11098
11099 SourceLocation Loc = Constructor->getEndLoc().isValid()
11100 ? Constructor->getEndLoc()
11101 : Constructor->getLocation();
11102 Constructor->setBody(new (Context) CompoundStmt(Loc));
11103 Constructor->markUsed(Context);
11104
11105 if (ASTMutationListener *L = getASTMutationListener()) {
11106 L->CompletedImplicitDefinition(Constructor);
11107 }
11108
11109 DiagnoseUninitializedFields(*this, Constructor);
11110}
11111
11112void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11113 // Perform any delayed checks on exception specifications.
11114 CheckDelayedMemberExceptionSpecs();
11115}
11116
11117/// Find or create the fake constructor we synthesize to model constructing an
11118/// object of a derived class via a constructor of a base class.
11119CXXConstructorDecl *
11120Sema::findInheritingConstructor(SourceLocation Loc,
11121 CXXConstructorDecl *BaseCtor,
11122 ConstructorUsingShadowDecl *Shadow) {
11123 CXXRecordDecl *Derived = Shadow->getParent();
11124 SourceLocation UsingLoc = Shadow->getLocation();
11125
11126 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11127 // For now we use the name of the base class constructor as a member of the
11128 // derived class to indicate a (fake) inherited constructor name.
11129 DeclarationName Name = BaseCtor->getDeclName();
11130
11131 // Check to see if we already have a fake constructor for this inherited
11132 // constructor call.
11133 for (NamedDecl *Ctor : Derived->lookup(Name))
11134 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11135 ->getInheritedConstructor()
11136 .getConstructor(),
11137 BaseCtor))
11138 return cast<CXXConstructorDecl>(Ctor);
11139
11140 DeclarationNameInfo NameInfo(Name, UsingLoc);
11141 TypeSourceInfo *TInfo =
11142 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11143 FunctionProtoTypeLoc ProtoLoc =
11144 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11145
11146 // Check the inherited constructor is valid and find the list of base classes
11147 // from which it was inherited.
11148 InheritedConstructorInfo ICI(*this, Loc, Shadow);
11149
11150 bool Constexpr =
11151 BaseCtor->isConstexpr() &&
11152 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11153 false, BaseCtor, &ICI);
11154
11155 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11156 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11157 BaseCtor->getExplicitSpecifier(), /*Inline=*/true,
11158 /*ImplicitlyDeclared=*/true, Constexpr,
11159 InheritedConstructor(Shadow, BaseCtor));
11160 if (Shadow->isInvalidDecl())
11161 DerivedCtor->setInvalidDecl();
11162
11163 // Build an unevaluated exception specification for this fake constructor.
11164 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11165 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11166 EPI.ExceptionSpec.Type = EST_Unevaluated;
11167 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11168 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11169 FPT->getParamTypes(), EPI));
11170
11171 // Build the parameter declarations.
11172 SmallVector<ParmVarDecl *, 16> ParamDecls;
11173 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11174 TypeSourceInfo *TInfo =
11175 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11176 ParmVarDecl *PD = ParmVarDecl::Create(
11177 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11178 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
11179 PD->setScopeInfo(0, I);
11180 PD->setImplicit();
11181 // Ensure attributes are propagated onto parameters (this matters for
11182 // format, pass_object_size, ...).
11183 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11184 ParamDecls.push_back(PD);
11185 ProtoLoc.setParam(I, PD);
11186 }
11187
11188 // Set up the new constructor.
11189 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11190 DerivedCtor->setAccess(BaseCtor->getAccess());
11191 DerivedCtor->setParams(ParamDecls);
11192 Derived->addDecl(DerivedCtor);
11193
11194 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11195 SetDeclDeleted(DerivedCtor, UsingLoc);
11196
11197 return DerivedCtor;
11198}
11199
11200void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11201 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11202 Ctor->getInheritedConstructor().getShadowDecl());
11203 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11204 /*Diagnose*/true);
11205}
11206
11207void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11208 CXXConstructorDecl *Constructor) {
11209 CXXRecordDecl *ClassDecl = Constructor->getParent();
11210 assert(Constructor->getInheritedConstructor() &&
11211 !Constructor->doesThisDeclarationHaveABody() &&
11212 !Constructor->isDeleted());
11213 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11214 return;
11215
11216 // Initializations are performed "as if by a defaulted default constructor",
11217 // so enter the appropriate scope.
11218 SynthesizedFunctionScope Scope(*this, Constructor);
11219
11220 // The exception specification is needed because we are defining the
11221 // function.
11222 ResolveExceptionSpec(CurrentLocation,
11223 Constructor->getType()->castAs<FunctionProtoType>());
11224 MarkVTableUsed(CurrentLocation, ClassDecl);
11225
11226 // Add a context note for diagnostics produced after this point.
11227 Scope.addContextNote(CurrentLocation);
11228
11229 ConstructorUsingShadowDecl *Shadow =
11230 Constructor->getInheritedConstructor().getShadowDecl();
11231 CXXConstructorDecl *InheritedCtor =
11232 Constructor->getInheritedConstructor().getConstructor();
11233
11234 // [class.inhctor.init]p1:
11235 // initialization proceeds as if a defaulted default constructor is used to
11236 // initialize the D object and each base class subobject from which the
11237 // constructor was inherited
11238
11239 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11240 CXXRecordDecl *RD = Shadow->getParent();
11241 SourceLocation InitLoc = Shadow->getLocation();
11242
11243 // Build explicit initializers for all base classes from which the
11244 // constructor was inherited.
11245 SmallVector<CXXCtorInitializer*, 8> Inits;
11246 for (bool VBase : {false, true}) {
11247 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11248 if (B.isVirtual() != VBase)
11249 continue;
11250
11251 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11252 if (!BaseRD)
11253 continue;
11254
11255 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11256 if (!BaseCtor.first)
11257 continue;
11258
11259 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11260 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11261 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11262
11263 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11264 Inits.push_back(new (Context) CXXCtorInitializer(
11265 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11266 SourceLocation()));
11267 }
11268 }
11269
11270 // We now proceed as if for a defaulted default constructor, with the relevant
11271 // initializers replaced.
11272
11273 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11274 Constructor->setInvalidDecl();
11275 return;
11276 }
11277
11278 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11279 Constructor->markUsed(Context);
11280
11281 if (ASTMutationListener *L = getASTMutationListener()) {
11282 L->CompletedImplicitDefinition(Constructor);
11283 }
11284
11285 DiagnoseUninitializedFields(*this, Constructor);
11286}
11287
11288CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11289 // C++ [class.dtor]p2:
11290 // If a class has no user-declared destructor, a destructor is
11291 // declared implicitly. An implicitly-declared destructor is an
11292 // inline public member of its class.
11293 assert(ClassDecl->needsImplicitDestructor());
11294
11295 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11296 if (DSM.isAlreadyBeingDeclared())
11297 return nullptr;
11298
11299 // Create the actual destructor declaration.
11300 CanQualType ClassType
11301 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11302 SourceLocation ClassLoc = ClassDecl->getLocation();
11303 DeclarationName Name
11304 = Context.DeclarationNames.getCXXDestructorName(ClassType);
11305 DeclarationNameInfo NameInfo(Name, ClassLoc);
11306 CXXDestructorDecl *Destructor
11307 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11308 QualType(), nullptr, /*isInline=*/true,
11309 /*isImplicitlyDeclared=*/true);
11310 Destructor->setAccess(AS_public);
11311 Destructor->setDefaulted();
11312
11313 if (getLangOpts().CUDA) {
11314 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11315 Destructor,
11316 /* ConstRHS */ false,
11317 /* Diagnose */ false);
11318 }
11319
11320 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11321
11322 // We don't need to use SpecialMemberIsTrivial here; triviality for
11323 // destructors is easy to compute.
11324 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11325 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11326 ClassDecl->hasTrivialDestructorForCall());
11327
11328 // Note that we have declared this destructor.
11329 ++getASTContext().NumImplicitDestructorsDeclared;
11330
11331 Scope *S = getScopeForContext(ClassDecl);
11332 CheckImplicitSpecialMemberDeclaration(S, Destructor);
11333
11334 // We can't check whether an implicit destructor is deleted before we complete
11335 // the definition of the class, because its validity depends on the alignment
11336 // of the class. We'll check this from ActOnFields once the class is complete.
11337 if (ClassDecl->isCompleteDefinition() &&
11338 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11339 SetDeclDeleted(Destructor, ClassLoc);
11340
11341 // Introduce this destructor into its scope.
11342 if (S)
11343 PushOnScopeChains(Destructor, S, false);
11344 ClassDecl->addDecl(Destructor);
11345
11346 return Destructor;
11347}
11348
11349void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11350 CXXDestructorDecl *Destructor) {
11351 assert((Destructor->isDefaulted() &&
11352 !Destructor->doesThisDeclarationHaveABody() &&
11353 !Destructor->isDeleted()) &&
11354 "DefineImplicitDestructor - call it for implicit default dtor");
11355 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11356 return;
11357
11358 CXXRecordDecl *ClassDecl = Destructor->getParent();
11359 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11360
11361 SynthesizedFunctionScope Scope(*this, Destructor);
11362
11363 // The exception specification is needed because we are defining the
11364 // function.
11365 ResolveExceptionSpec(CurrentLocation,
11366 Destructor->getType()->castAs<FunctionProtoType>());
11367 MarkVTableUsed(CurrentLocation, ClassDecl);
11368
11369 // Add a context note for diagnostics produced after this point.
11370 Scope.addContextNote(CurrentLocation);
11371
11372 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11373 Destructor->getParent());
11374
11375 if (CheckDestructor(Destructor)) {
11376 Destructor->setInvalidDecl();
11377 return;
11378 }
11379
11380 SourceLocation Loc = Destructor->getEndLoc().isValid()
11381 ? Destructor->getEndLoc()
11382 : Destructor->getLocation();
11383 Destructor->setBody(new (Context) CompoundStmt(Loc));
11384 Destructor->markUsed(Context);
11385
11386 if (ASTMutationListener *L = getASTMutationListener()) {
11387 L->CompletedImplicitDefinition(Destructor);
11388 }
11389}
11390
11391/// Perform any semantic analysis which needs to be delayed until all
11392/// pending class member declarations have been parsed.
11393void Sema::ActOnFinishCXXMemberDecls() {
11394 // If the context is an invalid C++ class, just suppress these checks.
11395 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11396 if (Record->isInvalidDecl()) {
11397 DelayedOverridingExceptionSpecChecks.clear();
11398 DelayedEquivalentExceptionSpecChecks.clear();
11399 return;
11400 }
11401 checkForMultipleExportedDefaultConstructors(*this, Record);
11402 }
11403}
11404
11405void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11406 referenceDLLExportedClassMethods();
11407}
11408
11409void Sema::referenceDLLExportedClassMethods() {
11410 if (!DelayedDllExportClasses.empty()) {
11411 // Calling ReferenceDllExportedMembers might cause the current function to
11412 // be called again, so use a local copy of DelayedDllExportClasses.
11413 SmallVector<CXXRecordDecl *, 4> WorkList;
11414 std::swap(DelayedDllExportClasses, WorkList);
11415 for (CXXRecordDecl *Class : WorkList)
11416 ReferenceDllExportedMembers(*this, Class);
11417 }
11418}
11419
11420void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11421 assert(getLangOpts().CPlusPlus11 &&
11422 "adjusting dtor exception specs was introduced in c++11");
11423
11424 if (Destructor->isDependentContext())
11425 return;
11426
11427 // C++11 [class.dtor]p3:
11428 // A declaration of a destructor that does not have an exception-
11429 // specification is implicitly considered to have the same exception-
11430 // specification as an implicit declaration.
11431 const FunctionProtoType *DtorType = Destructor->getType()->
11432 getAs<FunctionProtoType>();
11433 if (DtorType->hasExceptionSpec())
11434 return;
11435
11436 // Replace the destructor's type, building off the existing one. Fortunately,
11437 // the only thing of interest in the destructor type is its extended info.
11438 // The return and arguments are fixed.
11439 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11440 EPI.ExceptionSpec.Type = EST_Unevaluated;
11441 EPI.ExceptionSpec.SourceDecl = Destructor;
11442 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11443
11444 // FIXME: If the destructor has a body that could throw, and the newly created
11445 // spec doesn't allow exceptions, we should emit a warning, because this
11446 // change in behavior can break conforming C++03 programs at runtime.
11447 // However, we don't have a body or an exception specification yet, so it
11448 // needs to be done somewhere else.
11449}
11450
11451namespace {
11452/// An abstract base class for all helper classes used in building the
11453// copy/move operators. These classes serve as factory functions and help us
11454// avoid using the same Expr* in the AST twice.
11455class ExprBuilder {
11456 ExprBuilder(const ExprBuilder&) = delete;
11457 ExprBuilder &operator=(const ExprBuilder&) = delete;
11458
11459protected:
11460 static Expr *assertNotNull(Expr *E) {
11461 assert(E && "Expression construction must not fail.");
11462 return E;
11463 }
11464
11465public:
11466 ExprBuilder() {}
11467 virtual ~ExprBuilder() {}
11468
11469 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11470};
11471
11472class RefBuilder: public ExprBuilder {
11473 VarDecl *Var;
11474 QualType VarType;
11475
11476public:
11477 Expr *build(Sema &S, SourceLocation Loc) const override {
11478 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11479 }
11480
11481 RefBuilder(VarDecl *Var, QualType VarType)
11482 : Var(Var), VarType(VarType) {}
11483};
11484
11485class ThisBuilder: public ExprBuilder {
11486public:
11487 Expr *build(Sema &S, SourceLocation Loc) const override {
11488 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11489 }
11490};
11491
11492class CastBuilder: public ExprBuilder {
11493 const ExprBuilder &Builder;
11494 QualType Type;
11495 ExprValueKind Kind;
11496 const CXXCastPath &Path;
11497
11498public:
11499 Expr *build(Sema &S, SourceLocation Loc) const override {
11500 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11501 CK_UncheckedDerivedToBase, Kind,
11502 &Path).get());
11503 }
11504
11505 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11506 const CXXCastPath &Path)
11507 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11508};
11509
11510class DerefBuilder: public ExprBuilder {
11511 const ExprBuilder &Builder;
11512
11513public:
11514 Expr *build(Sema &S, SourceLocation Loc) const override {
11515 return assertNotNull(
11516 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11517 }
11518
11519 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11520};
11521
11522class MemberBuilder: public ExprBuilder {
11523 const ExprBuilder &Builder;
11524 QualType Type;
11525 CXXScopeSpec SS;
11526 bool IsArrow;
11527 LookupResult &MemberLookup;
11528
11529public:
11530 Expr *build(Sema &S, SourceLocation Loc) const override {
11531 return assertNotNull(S.BuildMemberReferenceExpr(
11532 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11533 nullptr, MemberLookup, nullptr, nullptr).get());
11534 }
11535
11536 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11537 LookupResult &MemberLookup)
11538 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11539 MemberLookup(MemberLookup) {}
11540};
11541
11542class MoveCastBuilder: public ExprBuilder {
11543 const ExprBuilder &Builder;
11544
11545public:
11546 Expr *build(Sema &S, SourceLocation Loc) const override {
11547 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11548 }
11549
11550 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11551};
11552
11553class LvalueConvBuilder: public ExprBuilder {
11554 const ExprBuilder &Builder;
11555
11556public:
11557 Expr *build(Sema &S, SourceLocation Loc) const override {
11558 return assertNotNull(
11559 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11560 }
11561
11562 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11563};
11564
11565class SubscriptBuilder: public ExprBuilder {
11566 const ExprBuilder &Base;
11567 const ExprBuilder &Index;
11568
11569public:
11570 Expr *build(Sema &S, SourceLocation Loc) const override {
11571 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11572 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11573 }
11574
11575 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11576 : Base(Base), Index(Index) {}
11577};
11578
11579} // end anonymous namespace
11580
11581/// When generating a defaulted copy or move assignment operator, if a field
11582/// should be copied with __builtin_memcpy rather than via explicit assignments,
11583/// do so. This optimization only applies for arrays of scalars, and for arrays
11584/// of class type where the selected copy/move-assignment operator is trivial.
11585static StmtResult
11586buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11587 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11588 // Compute the size of the memory buffer to be copied.
11589 QualType SizeType = S.Context.getSizeType();
11590 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11591 S.Context.getTypeSizeInChars(T).getQuantity());
11592
11593 // Take the address of the field references for "from" and "to". We
11594 // directly construct UnaryOperators here because semantic analysis
11595 // does not permit us to take the address of an xvalue.
11596 Expr *From = FromB.build(S, Loc);
11597 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11598 S.Context.getPointerType(From->getType()),
11599 VK_RValue, OK_Ordinary, Loc, false);
11600 Expr *To = ToB.build(S, Loc);
11601 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11602 S.Context.getPointerType(To->getType()),
11603 VK_RValue, OK_Ordinary, Loc, false);
11604
11605 const Type *E = T->getBaseElementTypeUnsafe();
11606 bool NeedsCollectableMemCpy =
11607 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11608
11609 // Create a reference to the __builtin_objc_memmove_collectable function
11610 StringRef MemCpyName = NeedsCollectableMemCpy ?
11611 "__builtin_objc_memmove_collectable" :
11612 "__builtin_memcpy";
11613 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11614 Sema::LookupOrdinaryName);
11615 S.LookupName(R, S.TUScope, true);
11616
11617 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11618 if (!MemCpy)
11619 // Something went horribly wrong earlier, and we will have complained
11620 // about it.
11621 return StmtError();
11622
11623 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11624 VK_RValue, Loc, nullptr);
11625 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11626
11627 Expr *CallArgs[] = {
11628 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11629 };
11630 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11631 Loc, CallArgs, Loc);
11632
11633 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11634 return Call.getAs<Stmt>();
11635}
11636
11637/// Builds a statement that copies/moves the given entity from \p From to
11638/// \c To.
11639///
11640/// This routine is used to copy/move the members of a class with an
11641/// implicitly-declared copy/move assignment operator. When the entities being
11642/// copied are arrays, this routine builds for loops to copy them.
11643///
11644/// \param S The Sema object used for type-checking.
11645///
11646/// \param Loc The location where the implicit copy/move is being generated.
11647///
11648/// \param T The type of the expressions being copied/moved. Both expressions
11649/// must have this type.
11650///
11651/// \param To The expression we are copying/moving to.
11652///
11653/// \param From The expression we are copying/moving from.
11654///
11655/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11656/// Otherwise, it's a non-static member subobject.
11657///
11658/// \param Copying Whether we're copying or moving.
11659///
11660/// \param Depth Internal parameter recording the depth of the recursion.
11661///
11662/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11663/// if a memcpy should be used instead.
11664static StmtResult
11665buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11666 const ExprBuilder &To, const ExprBuilder &From,
11667 bool CopyingBaseSubobject, bool Copying,
11668 unsigned Depth = 0) {
11669 // C++11 [class.copy]p28:
11670 // Each subobject is assigned in the manner appropriate to its type:
11671 //
11672 // - if the subobject is of class type, as if by a call to operator= with
11673 // the subobject as the object expression and the corresponding
11674 // subobject of x as a single function argument (as if by explicit
11675 // qualification; that is, ignoring any possible virtual overriding
11676 // functions in more derived classes);
11677 //
11678 // C++03 [class.copy]p13:
11679 // - if the subobject is of class type, the copy assignment operator for
11680 // the class is used (as if by explicit qualification; that is,
11681 // ignoring any possible virtual overriding functions in more derived
11682 // classes);
11683 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11684 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11685
11686 // Look for operator=.
11687 DeclarationName Name
11688 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11689 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11690 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11691
11692 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11693 // operator.
11694 if (!S.getLangOpts().CPlusPlus11) {
11695 LookupResult::Filter F = OpLookup.makeFilter();
11696 while (F.hasNext()) {
11697 NamedDecl *D = F.next();
11698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11699 if (Method->isCopyAssignmentOperator() ||
11700 (!Copying && Method->isMoveAssignmentOperator()))
11701 continue;
11702
11703 F.erase();
11704 }
11705 F.done();
11706 }
11707
11708 // Suppress the protected check (C++ [class.protected]) for each of the
11709 // assignment operators we found. This strange dance is required when
11710 // we're assigning via a base classes's copy-assignment operator. To
11711 // ensure that we're getting the right base class subobject (without
11712 // ambiguities), we need to cast "this" to that subobject type; to
11713 // ensure that we don't go through the virtual call mechanism, we need
11714 // to qualify the operator= name with the base class (see below). However,
11715 // this means that if the base class has a protected copy assignment
11716 // operator, the protected member access check will fail. So, we
11717 // rewrite "protected" access to "public" access in this case, since we
11718 // know by construction that we're calling from a derived class.
11719 if (CopyingBaseSubobject) {
11720 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11721 L != LEnd; ++L) {
11722 if (L.getAccess() == AS_protected)
11723 L.setAccess(AS_public);
11724 }
11725 }
11726
11727 // Create the nested-name-specifier that will be used to qualify the
11728 // reference to operator=; this is required to suppress the virtual
11729 // call mechanism.
11730 CXXScopeSpec SS;
11731 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11732 SS.MakeTrivial(S.Context,
11733 NestedNameSpecifier::Create(S.Context, nullptr, false,
11734 CanonicalT),
11735 Loc);
11736
11737 // Create the reference to operator=.
11738 ExprResult OpEqualRef
11739 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11740 SS, /*TemplateKWLoc=*/SourceLocation(),
11741 /*FirstQualifierInScope=*/nullptr,
11742 OpLookup,
11743 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11744 /*SuppressQualifierCheck=*/true);
11745 if (OpEqualRef.isInvalid())
11746 return StmtError();
11747
11748 // Build the call to the assignment operator.
11749
11750 Expr *FromInst = From.build(S, Loc);
11751 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11752 OpEqualRef.getAs<Expr>(),
11753 Loc, FromInst, Loc);
11754 if (Call.isInvalid())
11755 return StmtError();
11756
11757 // If we built a call to a trivial 'operator=' while copying an array,
11758 // bail out. We'll replace the whole shebang with a memcpy.
11759 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11760 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11761 return StmtResult((Stmt*)nullptr);
11762
11763 // Convert to an expression-statement, and clean up any produced
11764 // temporaries.
11765 return S.ActOnExprStmt(Call);
11766 }
11767
11768 // - if the subobject is of scalar type, the built-in assignment
11769 // operator is used.
11770 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11771 if (!ArrayTy) {
11772 ExprResult Assignment = S.CreateBuiltinBinOp(
11773 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11774 if (Assignment.isInvalid())
11775 return StmtError();
11776 return S.ActOnExprStmt(Assignment);
11777 }
11778
11779 // - if the subobject is an array, each element is assigned, in the
11780 // manner appropriate to the element type;
11781
11782 // Construct a loop over the array bounds, e.g.,
11783 //
11784 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11785 //
11786 // that will copy each of the array elements.
11787 QualType SizeType = S.Context.getSizeType();
11788
11789 // Create the iteration variable.
11790 IdentifierInfo *IterationVarName = nullptr;
11791 {
11792 SmallString<8> Str;
11793 llvm::raw_svector_ostream OS(Str);
11794 OS << "__i" << Depth;
11795 IterationVarName = &S.Context.Idents.get(OS.str());
11796 }
11797 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11798 IterationVarName, SizeType,
11799 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11800 SC_None);
11801
11802 // Initialize the iteration variable to zero.
11803 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11804 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11805
11806 // Creates a reference to the iteration variable.
11807 RefBuilder IterationVarRef(IterationVar, SizeType);
11808 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11809
11810 // Create the DeclStmt that holds the iteration variable.
11811 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11812
11813 // Subscript the "from" and "to" expressions with the iteration variable.
11814 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11815 MoveCastBuilder FromIndexMove(FromIndexCopy);
11816 const ExprBuilder *FromIndex;
11817 if (Copying)
11818 FromIndex = &FromIndexCopy;
11819 else
11820 FromIndex = &FromIndexMove;
11821
11822 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11823
11824 // Build the copy/move for an individual element of the array.
11825 StmtResult Copy =
11826 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11827 ToIndex, *FromIndex, CopyingBaseSubobject,
11828 Copying, Depth + 1);
11829 // Bail out if copying fails or if we determined that we should use memcpy.
11830 if (Copy.isInvalid() || !Copy.get())
11831 return Copy;
11832
11833 // Create the comparison against the array bound.
11834 llvm::APInt Upper
11835 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11836 Expr *Comparison
11837 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11838 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11839 BO_NE, S.Context.BoolTy,
11840 VK_RValue, OK_Ordinary, Loc, FPOptions());
11841
11842 // Create the pre-increment of the iteration variable. We can determine
11843 // whether the increment will overflow based on the value of the array
11844 // bound.
11845 Expr *Increment = new (S.Context)
11846 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11847 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11848
11849 // Construct the loop that copies all elements of this array.
11850 return S.ActOnForStmt(
11851 Loc, Loc, InitStmt,
11852 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11853 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11854}
11855
11856static StmtResult
11857buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11858 const ExprBuilder &To, const ExprBuilder &From,
11859 bool CopyingBaseSubobject, bool Copying) {
11860 // Maybe we should use a memcpy?
11861 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11862 T.isTriviallyCopyableType(S.Context))
11863 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11864
11865 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11866 CopyingBaseSubobject,
11867 Copying, 0));
11868
11869 // If we ended up picking a trivial assignment operator for an array of a
11870 // non-trivially-copyable class type, just emit a memcpy.
11871 if (!Result.isInvalid() && !Result.get())
11872 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11873
11874 return Result;
11875}
11876
11877CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11878 // Note: The following rules are largely analoguous to the copy
11879 // constructor rules. Note that virtual bases are not taken into account
11880 // for determining the argument type of the operator. Note also that
11881 // operators taking an object instead of a reference are allowed.
11882 assert(ClassDecl->needsImplicitCopyAssignment());
11883
11884 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11885 if (DSM.isAlreadyBeingDeclared())
11886 return nullptr;
11887
11888 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11889 if (Context.getLangOpts().OpenCLCPlusPlus)
11890 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11891 QualType RetType = Context.getLValueReferenceType(ArgType);
11892 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11893 if (Const)
11894 ArgType = ArgType.withConst();
11895
11896 ArgType = Context.getLValueReferenceType(ArgType);
11897
11898 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11899 CXXCopyAssignment,
11900 Const);
11901
11902 // An implicitly-declared copy assignment operator is an inline public
11903 // member of its class.
11904 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11905 SourceLocation ClassLoc = ClassDecl->getLocation();
11906 DeclarationNameInfo NameInfo(Name, ClassLoc);
11907 CXXMethodDecl *CopyAssignment =
11908 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11909 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11910 /*isInline=*/true, Constexpr, SourceLocation());
11911 CopyAssignment->setAccess(AS_public);
11912 CopyAssignment->setDefaulted();
11913 CopyAssignment->setImplicit();
11914
11915 if (getLangOpts().CUDA) {
11916 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11917 CopyAssignment,
11918 /* ConstRHS */ Const,
11919 /* Diagnose */ false);
11920 }
11921
11922 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11923
11924 // Add the parameter to the operator.
11925 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11926 ClassLoc, ClassLoc,
11927 /*Id=*/nullptr, ArgType,
11928 /*TInfo=*/nullptr, SC_None,
11929 nullptr);
11930 CopyAssignment->setParams(FromParam);
11931
11932 CopyAssignment->setTrivial(
11933 ClassDecl->needsOverloadResolutionForCopyAssignment()
11934 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11935 : ClassDecl->hasTrivialCopyAssignment());
11936
11937 // Note that we have added this copy-assignment operator.
11938 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11939
11940 Scope *S = getScopeForContext(ClassDecl);
11941 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11942
11943 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11944 SetDeclDeleted(CopyAssignment, ClassLoc);
11945
11946 if (S)
11947 PushOnScopeChains(CopyAssignment, S, false);
11948 ClassDecl->addDecl(CopyAssignment);
11949
11950 return CopyAssignment;
11951}
11952
11953/// Diagnose an implicit copy operation for a class which is odr-used, but
11954/// which is deprecated because the class has a user-declared copy constructor,
11955/// copy assignment operator, or destructor.
11956static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11957 assert(CopyOp->isImplicit());
11958
11959 CXXRecordDecl *RD = CopyOp->getParent();
11960 CXXMethodDecl *UserDeclaredOperation = nullptr;
11961
11962 // In Microsoft mode, assignment operations don't affect constructors and
11963 // vice versa.
11964 if (RD->hasUserDeclaredDestructor()) {
11965 UserDeclaredOperation = RD->getDestructor();
11966 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11967 RD->hasUserDeclaredCopyConstructor() &&
11968 !S.getLangOpts().MSVCCompat) {
11969 // Find any user-declared copy constructor.
11970 for (auto *I : RD->ctors()) {
11971 if (I->isCopyConstructor()) {
11972 UserDeclaredOperation = I;
11973 break;
11974 }
11975 }
11976 assert(UserDeclaredOperation);
11977 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11978 RD->hasUserDeclaredCopyAssignment() &&
11979 !S.getLangOpts().MSVCCompat) {
11980 // Find any user-declared move assignment operator.
11981 for (auto *I : RD->methods()) {
11982 if (I->isCopyAssignmentOperator()) {
11983 UserDeclaredOperation = I;
11984 break;
11985 }
11986 }
11987 assert(UserDeclaredOperation);
11988 }
11989
11990 if (UserDeclaredOperation) {
11991 S.Diag(UserDeclaredOperation->getLocation(),
11992 diag::warn_deprecated_copy_operation)
11993 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11994 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11995 }
11996}
11997
11998void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11999 CXXMethodDecl *CopyAssignOperator) {
12000 assert((CopyAssignOperator->isDefaulted() &&
12001 CopyAssignOperator->isOverloadedOperator() &&
12002 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12003 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12004 !CopyAssignOperator->isDeleted()) &&
12005 "DefineImplicitCopyAssignment called for wrong function");
12006 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12007 return;
12008
12009 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12010 if (ClassDecl->isInvalidDecl()) {
12011 CopyAssignOperator->setInvalidDecl();
12012 return;
12013 }
12014
12015 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12016
12017 // The exception specification is needed because we are defining the
12018 // function.
12019 ResolveExceptionSpec(CurrentLocation,
12020 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12021
12022 // Add a context note for diagnostics produced after this point.
12023 Scope.addContextNote(CurrentLocation);
12024
12025 // C++11 [class.copy]p18:
12026 // The [definition of an implicitly declared copy assignment operator] is
12027 // deprecated if the class has a user-declared copy constructor or a
12028 // user-declared destructor.
12029 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12030 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12031
12032 // C++0x [class.copy]p30:
12033 // The implicitly-defined or explicitly-defaulted copy assignment operator
12034 // for a non-union class X performs memberwise copy assignment of its
12035 // subobjects. The direct base classes of X are assigned first, in the
12036 // order of their declaration in the base-specifier-list, and then the
12037 // immediate non-static data members of X are assigned, in the order in
12038 // which they were declared in the class definition.
12039
12040 // The statements that form the synthesized function body.
12041 SmallVector<Stmt*, 8> Statements;
12042
12043 // The parameter for the "other" object, which we are copying from.
12044 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12045 Qualifiers OtherQuals = Other->getType().getQualifiers();
12046 QualType OtherRefType = Other->getType();
12047 if (const LValueReferenceType *OtherRef
12048 = OtherRefType->getAs<LValueReferenceType>()) {
12049 OtherRefType = OtherRef->getPointeeType();
12050 OtherQuals = OtherRefType.getQualifiers();
12051 }
12052
12053 // Our location for everything implicitly-generated.
12054 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12055 ? CopyAssignOperator->getEndLoc()
12056 : CopyAssignOperator->getLocation();
12057
12058 // Builds a DeclRefExpr for the "other" object.
12059 RefBuilder OtherRef(Other, OtherRefType);
12060
12061 // Builds the "this" pointer.
12062 ThisBuilder This;
12063
12064 // Assign base classes.
12065 bool Invalid = false;
12066 for (auto &Base : ClassDecl->bases()) {
12067 // Form the assignment:
12068 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12069 QualType BaseType = Base.getType().getUnqualifiedType();
12070 if (!BaseType->isRecordType()) {
12071 Invalid = true;
12072 continue;
12073 }
12074
12075 CXXCastPath BasePath;
12076 BasePath.push_back(&Base);
12077
12078 // Construct the "from" expression, which is an implicit cast to the
12079 // appropriately-qualified base type.
12080 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12081 VK_LValue, BasePath);
12082
12083 // Dereference "this".
12084 DerefBuilder DerefThis(This);
12085 CastBuilder To(DerefThis,
12086 Context.getQualifiedType(
12087 BaseType, CopyAssignOperator->getMethodQualifiers()),
12088 VK_LValue, BasePath);
12089
12090 // Build the copy.
12091 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12092 To, From,
12093 /*CopyingBaseSubobject=*/true,
12094 /*Copying=*/true);
12095 if (Copy.isInvalid()) {
12096 CopyAssignOperator->setInvalidDecl();
12097 return;
12098 }
12099
12100 // Success! Record the copy.
12101 Statements.push_back(Copy.getAs<Expr>());
12102 }
12103
12104 // Assign non-static members.
12105 for (auto *Field : ClassDecl->fields()) {
12106 // FIXME: We should form some kind of AST representation for the implied
12107 // memcpy in a union copy operation.
12108 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12109 continue;
12110
12111 if (Field->isInvalidDecl()) {
12112 Invalid = true;
12113 continue;
12114 }
12115
12116 // Check for members of reference type; we can't copy those.
12117 if (Field->getType()->isReferenceType()) {
12118 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12119 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12120 Diag(Field->getLocation(), diag::note_declared_at);
12121 Invalid = true;
12122 continue;
12123 }
12124
12125 // Check for members of const-qualified, non-class type.
12126 QualType BaseType = Context.getBaseElementType(Field->getType());
12127 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12128 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12129 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12130 Diag(Field->getLocation(), diag::note_declared_at);
12131 Invalid = true;
12132 continue;
12133 }
12134
12135 // Suppress assigning zero-width bitfields.
12136 if (Field->isZeroLengthBitField(Context))
12137 continue;
12138
12139 QualType FieldType = Field->getType().getNonReferenceType();
12140 if (FieldType->isIncompleteArrayType()) {
12141 assert(ClassDecl->hasFlexibleArrayMember() &&
12142 "Incomplete array type is not valid");
12143 continue;
12144 }
12145
12146 // Build references to the field in the object we're copying from and to.
12147 CXXScopeSpec SS; // Intentionally empty
12148 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12149 LookupMemberName);
12150 MemberLookup.addDecl(Field);
12151 MemberLookup.resolveKind();
12152
12153 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12154
12155 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12156
12157 // Build the copy of this field.
12158 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12159 To, From,
12160 /*CopyingBaseSubobject=*/false,
12161 /*Copying=*/true);
12162 if (Copy.isInvalid()) {
12163 CopyAssignOperator->setInvalidDecl();
12164 return;
12165 }
12166
12167 // Success! Record the copy.
12168 Statements.push_back(Copy.getAs<Stmt>());
12169 }
12170
12171 if (!Invalid) {
12172 // Add a "return *this;"
12173 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12174
12175 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12176 if (Return.isInvalid())
12177 Invalid = true;
12178 else
12179 Statements.push_back(Return.getAs<Stmt>());
12180 }
12181
12182 if (Invalid) {
12183 CopyAssignOperator->setInvalidDecl();
12184 return;
12185 }
12186
12187 StmtResult Body;
12188 {
12189 CompoundScopeRAII CompoundScope(*this);
12190 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12191 /*isStmtExpr=*/false);
12192 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12193 }
12194 CopyAssignOperator->setBody(Body.getAs<Stmt>());
12195 CopyAssignOperator->markUsed(Context);
12196
12197 if (ASTMutationListener *L = getASTMutationListener()) {
12198 L->CompletedImplicitDefinition(CopyAssignOperator);
12199 }
12200}
12201
12202CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12203 assert(ClassDecl->needsImplicitMoveAssignment());
12204
12205 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12206 if (DSM.isAlreadyBeingDeclared())
12207 return nullptr;
12208
12209 // Note: The following rules are largely analoguous to the move
12210 // constructor rules.
12211
12212 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12213 if (Context.getLangOpts().OpenCLCPlusPlus)
12214 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12215 QualType RetType = Context.getLValueReferenceType(ArgType);
12216 ArgType = Context.getRValueReferenceType(ArgType);
12217
12218 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12219 CXXMoveAssignment,
12220 false);
12221
12222 // An implicitly-declared move assignment operator is an inline public
12223 // member of its class.
12224 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12225 SourceLocation ClassLoc = ClassDecl->getLocation();
12226 DeclarationNameInfo NameInfo(Name, ClassLoc);
12227 CXXMethodDecl *MoveAssignment =
12228 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12229 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12230 /*isInline=*/true, Constexpr, SourceLocation());
12231 MoveAssignment->setAccess(AS_public);
12232 MoveAssignment->setDefaulted();
12233 MoveAssignment->setImplicit();
12234
12235 if (getLangOpts().CUDA) {
12236 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12237 MoveAssignment,
12238 /* ConstRHS */ false,
12239 /* Diagnose */ false);
12240 }
12241
12242 // Build an exception specification pointing back at this member.
12243 FunctionProtoType::ExtProtoInfo EPI =
12244 getImplicitMethodEPI(*this, MoveAssignment);
12245 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12246
12247 // Add the parameter to the operator.
12248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12249 ClassLoc, ClassLoc,
12250 /*Id=*/nullptr, ArgType,
12251 /*TInfo=*/nullptr, SC_None,
12252 nullptr);
12253 MoveAssignment->setParams(FromParam);
12254
12255 MoveAssignment->setTrivial(
12256 ClassDecl->needsOverloadResolutionForMoveAssignment()
12257 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12258 : ClassDecl->hasTrivialMoveAssignment());
12259
12260 // Note that we have added this copy-assignment operator.
12261 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12262
12263 Scope *S = getScopeForContext(ClassDecl);
12264 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12265
12266 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12267 ClassDecl->setImplicitMoveAssignmentIsDeleted();
12268 SetDeclDeleted(MoveAssignment, ClassLoc);
12269 }
12270
12271 if (S)
12272 PushOnScopeChains(MoveAssignment, S, false);
12273 ClassDecl->addDecl(MoveAssignment);
12274
12275 return MoveAssignment;
12276}
12277
12278/// Check if we're implicitly defining a move assignment operator for a class
12279/// with virtual bases. Such a move assignment might move-assign the virtual
12280/// base multiple times.
12281static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12282 SourceLocation CurrentLocation) {
12283 assert(!Class->isDependentContext() && "should not define dependent move");
12284
12285 // Only a virtual base could get implicitly move-assigned multiple times.
12286 // Only a non-trivial move assignment can observe this. We only want to
12287 // diagnose if we implicitly define an assignment operator that assigns
12288 // two base classes, both of which move-assign the same virtual base.
12289 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12290 Class->getNumBases() < 2)
12291 return;
12292
12293 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12294 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12295 VBaseMap VBases;
12296
12297 for (auto &BI : Class->bases()) {
12298 Worklist.push_back(&BI);
12299 while (!Worklist.empty()) {
12300 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12301 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12302
12303 // If the base has no non-trivial move assignment operators,
12304 // we don't care about moves from it.
12305 if (!Base->hasNonTrivialMoveAssignment())
12306 continue;
12307
12308 // If there's nothing virtual here, skip it.
12309 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12310 continue;
12311
12312 // If we're not actually going to call a move assignment for this base,
12313 // or the selected move assignment is trivial, skip it.
12314 Sema::SpecialMemberOverloadResult SMOR =
12315 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12316 /*ConstArg*/false, /*VolatileArg*/false,
12317 /*RValueThis*/true, /*ConstThis*/false,
12318 /*VolatileThis*/false);
12319 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12320 !SMOR.getMethod()->isMoveAssignmentOperator())
12321 continue;
12322
12323 if (BaseSpec->isVirtual()) {
12324 // We're going to move-assign this virtual base, and its move
12325 // assignment operator is not trivial. If this can happen for
12326 // multiple distinct direct bases of Class, diagnose it. (If it
12327 // only happens in one base, we'll diagnose it when synthesizing
12328 // that base class's move assignment operator.)
12329 CXXBaseSpecifier *&Existing =
12330 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12331 .first->second;
12332 if (Existing && Existing != &BI) {
12333 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12334 << Class << Base;
12335 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12336 << (Base->getCanonicalDecl() ==
12337 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12338 << Base << Existing->getType() << Existing->getSourceRange();
12339 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12340 << (Base->getCanonicalDecl() ==
12341 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12342 << Base << BI.getType() << BaseSpec->getSourceRange();
12343
12344 // Only diagnose each vbase once.
12345 Existing = nullptr;
12346 }
12347 } else {
12348 // Only walk over bases that have defaulted move assignment operators.
12349 // We assume that any user-provided move assignment operator handles
12350 // the multiple-moves-of-vbase case itself somehow.
12351 if (!SMOR.getMethod()->isDefaulted())
12352 continue;
12353
12354 // We're going to move the base classes of Base. Add them to the list.
12355 for (auto &BI : Base->bases())
12356 Worklist.push_back(&BI);
12357 }
12358 }
12359 }
12360}
12361
12362void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12363 CXXMethodDecl *MoveAssignOperator) {
12364 assert((MoveAssignOperator->isDefaulted() &&
12365 MoveAssignOperator->isOverloadedOperator() &&
12366 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12367 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12368 !MoveAssignOperator->isDeleted()) &&
12369 "DefineImplicitMoveAssignment called for wrong function");
12370 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12371 return;
12372
12373 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12374 if (ClassDecl->isInvalidDecl()) {
12375 MoveAssignOperator->setInvalidDecl();
12376 return;
12377 }
12378
12379 // C++0x [class.copy]p28:
12380 // The implicitly-defined or move assignment operator for a non-union class
12381 // X performs memberwise move assignment of its subobjects. The direct base
12382 // classes of X are assigned first, in the order of their declaration in the
12383 // base-specifier-list, and then the immediate non-static data members of X
12384 // are assigned, in the order in which they were declared in the class
12385 // definition.
12386
12387 // Issue a warning if our implicit move assignment operator will move
12388 // from a virtual base more than once.
12389 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12390
12391 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12392
12393 // The exception specification is needed because we are defining the
12394 // function.
12395 ResolveExceptionSpec(CurrentLocation,
12396 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12397
12398 // Add a context note for diagnostics produced after this point.
12399 Scope.addContextNote(CurrentLocation);
12400
12401 // The statements that form the synthesized function body.
12402 SmallVector<Stmt*, 8> Statements;
12403
12404 // The parameter for the "other" object, which we are move from.
12405 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12406 QualType OtherRefType = Other->getType()->
12407 getAs<RValueReferenceType>()->getPointeeType();
12408
12409 // Our location for everything implicitly-generated.
12410 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12411 ? MoveAssignOperator->getEndLoc()
12412 : MoveAssignOperator->getLocation();
12413
12414 // Builds a reference to the "other" object.
12415 RefBuilder OtherRef(Other, OtherRefType);
12416 // Cast to rvalue.
12417 MoveCastBuilder MoveOther(OtherRef);
12418
12419 // Builds the "this" pointer.
12420 ThisBuilder This;
12421
12422 // Assign base classes.
12423 bool Invalid = false;
12424 for (auto &Base : ClassDecl->bases()) {
12425 // C++11 [class.copy]p28:
12426 // It is unspecified whether subobjects representing virtual base classes
12427 // are assigned more than once by the implicitly-defined copy assignment
12428 // operator.
12429 // FIXME: Do not assign to a vbase that will be assigned by some other base
12430 // class. For a move-assignment, this can result in the vbase being moved
12431 // multiple times.
12432
12433 // Form the assignment:
12434 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12435 QualType BaseType = Base.getType().getUnqualifiedType();
12436 if (!BaseType->isRecordType()) {
12437 Invalid = true;
12438 continue;
12439 }
12440
12441 CXXCastPath BasePath;
12442 BasePath.push_back(&Base);
12443
12444 // Construct the "from" expression, which is an implicit cast to the
12445 // appropriately-qualified base type.
12446 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12447
12448 // Dereference "this".
12449 DerefBuilder DerefThis(This);
12450
12451 // Implicitly cast "this" to the appropriately-qualified base type.
12452 CastBuilder To(DerefThis,
12453 Context.getQualifiedType(
12454 BaseType, MoveAssignOperator->getMethodQualifiers()),
12455 VK_LValue, BasePath);
12456
12457 // Build the move.
12458 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12459 To, From,
12460 /*CopyingBaseSubobject=*/true,
12461 /*Copying=*/false);
12462 if (Move.isInvalid()) {
12463 MoveAssignOperator->setInvalidDecl();
12464 return;
12465 }
12466
12467 // Success! Record the move.
12468 Statements.push_back(Move.getAs<Expr>());
12469 }
12470
12471 // Assign non-static members.
12472 for (auto *Field : ClassDecl->fields()) {
12473 // FIXME: We should form some kind of AST representation for the implied
12474 // memcpy in a union copy operation.
12475 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12476 continue;
12477
12478 if (Field->isInvalidDecl()) {
12479 Invalid = true;
12480 continue;
12481 }
12482
12483 // Check for members of reference type; we can't move those.
12484 if (Field->getType()->isReferenceType()) {
12485 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12486 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12487 Diag(Field->getLocation(), diag::note_declared_at);
12488 Invalid = true;
12489 continue;
12490 }
12491
12492 // Check for members of const-qualified, non-class type.
12493 QualType BaseType = Context.getBaseElementType(Field->getType());
12494 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12495 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12496 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12497 Diag(Field->getLocation(), diag::note_declared_at);
12498 Invalid = true;
12499 continue;
12500 }
12501
12502 // Suppress assigning zero-width bitfields.
12503 if (Field->isZeroLengthBitField(Context))
12504 continue;
12505
12506 QualType FieldType = Field->getType().getNonReferenceType();
12507 if (FieldType->isIncompleteArrayType()) {
12508 assert(ClassDecl->hasFlexibleArrayMember() &&
12509 "Incomplete array type is not valid");
12510 continue;
12511 }
12512
12513 // Build references to the field in the object we're copying from and to.
12514 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12515 LookupMemberName);
12516 MemberLookup.addDecl(Field);
12517 MemberLookup.resolveKind();
12518 MemberBuilder From(MoveOther, OtherRefType,
12519 /*IsArrow=*/false, MemberLookup);
12520 MemberBuilder To(This, getCurrentThisType(),
12521 /*IsArrow=*/true, MemberLookup);
12522
12523 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12524 "Member reference with rvalue base must be rvalue except for reference "
12525 "members, which aren't allowed for move assignment.");
12526
12527 // Build the move of this field.
12528 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12529 To, From,
12530 /*CopyingBaseSubobject=*/false,
12531 /*Copying=*/false);
12532 if (Move.isInvalid()) {
12533 MoveAssignOperator->setInvalidDecl();
12534 return;
12535 }
12536
12537 // Success! Record the copy.
12538 Statements.push_back(Move.getAs<Stmt>());
12539 }
12540
12541 if (!Invalid) {
12542 // Add a "return *this;"
12543 ExprResult ThisObj =
12544 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12545
12546 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12547 if (Return.isInvalid())
12548 Invalid = true;
12549 else
12550 Statements.push_back(Return.getAs<Stmt>());
12551 }
12552
12553 if (Invalid) {
12554 MoveAssignOperator->setInvalidDecl();
12555 return;
12556 }
12557
12558 StmtResult Body;
12559 {
12560 CompoundScopeRAII CompoundScope(*this);
12561 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12562 /*isStmtExpr=*/false);
12563 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12564 }
12565 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12566 MoveAssignOperator->markUsed(Context);
12567
12568 if (ASTMutationListener *L = getASTMutationListener()) {
12569 L->CompletedImplicitDefinition(MoveAssignOperator);
12570 }
12571}
12572
12573CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12574 CXXRecordDecl *ClassDecl) {
12575 // C++ [class.copy]p4:
12576 // If the class definition does not explicitly declare a copy
12577 // constructor, one is declared implicitly.
12578 assert(ClassDecl->needsImplicitCopyConstructor());
12579
12580 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12581 if (DSM.isAlreadyBeingDeclared())
12582 return nullptr;
12583
12584 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12585 QualType ArgType = ClassType;
12586 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12587 if (Const)
12588 ArgType = ArgType.withConst();
12589
12590 if (Context.getLangOpts().OpenCLCPlusPlus)
12591 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12592
12593 ArgType = Context.getLValueReferenceType(ArgType);
12594
12595 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12596 CXXCopyConstructor,
12597 Const);
12598
12599 DeclarationName Name
12600 = Context.DeclarationNames.getCXXConstructorName(
12601 Context.getCanonicalType(ClassType));
12602 SourceLocation ClassLoc = ClassDecl->getLocation();
12603 DeclarationNameInfo NameInfo(Name, ClassLoc);
12604
12605 // An implicitly-declared copy constructor is an inline public
12606 // member of its class.
12607 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12608 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12609 ExplicitSpecifier(),
12610 /*isInline=*/true,
12611 /*isImplicitlyDeclared=*/true, Constexpr);
12612 CopyConstructor->setAccess(AS_public);
12613 CopyConstructor->setDefaulted();
12614
12615 if (getLangOpts().CUDA) {
12616 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12617 CopyConstructor,
12618 /* ConstRHS */ Const,
12619 /* Diagnose */ false);
12620 }
12621
12622 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12623
12624 // Add the parameter to the constructor.
12625 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12626 ClassLoc, ClassLoc,
12627 /*IdentifierInfo=*/nullptr,
12628 ArgType, /*TInfo=*/nullptr,
12629 SC_None, nullptr);
12630 CopyConstructor->setParams(FromParam);
12631
12632 CopyConstructor->setTrivial(
12633 ClassDecl->needsOverloadResolutionForCopyConstructor()
12634 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12635 : ClassDecl->hasTrivialCopyConstructor());
12636
12637 CopyConstructor->setTrivialForCall(
12638 ClassDecl->hasAttr<TrivialABIAttr>() ||
12639 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12640 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12641 TAH_ConsiderTrivialABI)
12642 : ClassDecl->hasTrivialCopyConstructorForCall()));
12643
12644 // Note that we have declared this constructor.
12645 ++getASTContext().NumImplicitCopyConstructorsDeclared;
12646
12647 Scope *S = getScopeForContext(ClassDecl);
12648 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12649
12650 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12651 ClassDecl->setImplicitCopyConstructorIsDeleted();
12652 SetDeclDeleted(CopyConstructor, ClassLoc);
12653 }
12654
12655 if (S)
12656 PushOnScopeChains(CopyConstructor, S, false);
12657 ClassDecl->addDecl(CopyConstructor);
12658
12659 return CopyConstructor;
12660}
12661
12662void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12663 CXXConstructorDecl *CopyConstructor) {
12664 assert((CopyConstructor->isDefaulted() &&
12665 CopyConstructor->isCopyConstructor() &&
12666 !CopyConstructor->doesThisDeclarationHaveABody() &&
12667 !CopyConstructor->isDeleted()) &&
12668 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12669 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12670 return;
12671
12672 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12673 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12674
12675 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12676
12677 // The exception specification is needed because we are defining the
12678 // function.
12679 ResolveExceptionSpec(CurrentLocation,
12680 CopyConstructor->getType()->castAs<FunctionProtoType>());
12681 MarkVTableUsed(CurrentLocation, ClassDecl);
12682
12683 // Add a context note for diagnostics produced after this point.
12684 Scope.addContextNote(CurrentLocation);
12685
12686 // C++11 [class.copy]p7:
12687 // The [definition of an implicitly declared copy constructor] is
12688 // deprecated if the class has a user-declared copy assignment operator
12689 // or a user-declared destructor.
12690 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12691 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12692
12693 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12694 CopyConstructor->setInvalidDecl();
12695 } else {
12696 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12697 ? CopyConstructor->getEndLoc()
12698 : CopyConstructor->getLocation();
12699 Sema::CompoundScopeRAII CompoundScope(*this);
12700 CopyConstructor->setBody(
12701 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12702 CopyConstructor->markUsed(Context);
12703 }
12704
12705 if (ASTMutationListener *L = getASTMutationListener()) {
12706 L->CompletedImplicitDefinition(CopyConstructor);
12707 }
12708}
12709
12710CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12711 CXXRecordDecl *ClassDecl) {
12712 assert(ClassDecl->needsImplicitMoveConstructor());
12713
12714 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12715 if (DSM.isAlreadyBeingDeclared())
12716 return nullptr;
12717
12718 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12719
12720 QualType ArgType = ClassType;
12721 if (Context.getLangOpts().OpenCLCPlusPlus)
12722 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12723 ArgType = Context.getRValueReferenceType(ArgType);
12724
12725 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12726 CXXMoveConstructor,
12727 false);
12728
12729 DeclarationName Name
12730 = Context.DeclarationNames.getCXXConstructorName(
12731 Context.getCanonicalType(ClassType));
12732 SourceLocation ClassLoc = ClassDecl->getLocation();
12733 DeclarationNameInfo NameInfo(Name, ClassLoc);
12734
12735 // C++11 [class.copy]p11:
12736 // An implicitly-declared copy/move constructor is an inline public
12737 // member of its class.
12738 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12739 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12740 ExplicitSpecifier(),
12741 /*isInline=*/true,
12742 /*isImplicitlyDeclared=*/true, Constexpr);
12743 MoveConstructor->setAccess(AS_public);
12744 MoveConstructor->setDefaulted();
12745
12746 if (getLangOpts().CUDA) {
12747 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12748 MoveConstructor,
12749 /* ConstRHS */ false,
12750 /* Diagnose */ false);
12751 }
12752
12753 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12754
12755 // Add the parameter to the constructor.
12756 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12757 ClassLoc, ClassLoc,
12758 /*IdentifierInfo=*/nullptr,
12759 ArgType, /*TInfo=*/nullptr,
12760 SC_None, nullptr);
12761 MoveConstructor->setParams(FromParam);
12762
12763 MoveConstructor->setTrivial(
12764 ClassDecl->needsOverloadResolutionForMoveConstructor()
12765 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12766 : ClassDecl->hasTrivialMoveConstructor());
12767
12768 MoveConstructor->setTrivialForCall(
12769 ClassDecl->hasAttr<TrivialABIAttr>() ||
12770 (ClassDecl->needsOverloadResolutionForMoveConstructor()
12771 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12772 TAH_ConsiderTrivialABI)
12773 : ClassDecl->hasTrivialMoveConstructorForCall()));
12774
12775 // Note that we have declared this constructor.
12776 ++getASTContext().NumImplicitMoveConstructorsDeclared;
12777
12778 Scope *S = getScopeForContext(ClassDecl);
12779 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12780
12781 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12782 ClassDecl->setImplicitMoveConstructorIsDeleted();
12783 SetDeclDeleted(MoveConstructor, ClassLoc);
12784 }
12785
12786 if (S)
12787 PushOnScopeChains(MoveConstructor, S, false);
12788 ClassDecl->addDecl(MoveConstructor);
12789
12790 return MoveConstructor;
12791}
12792
12793void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12794 CXXConstructorDecl *MoveConstructor) {
12795 assert((MoveConstructor->isDefaulted() &&
12796 MoveConstructor->isMoveConstructor() &&
12797 !MoveConstructor->doesThisDeclarationHaveABody() &&
12798 !MoveConstructor->isDeleted()) &&
12799 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12800 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12801 return;
12802
12803 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12804 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12805
12806 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12807
12808 // The exception specification is needed because we are defining the
12809 // function.
12810 ResolveExceptionSpec(CurrentLocation,
12811 MoveConstructor->getType()->castAs<FunctionProtoType>());
12812 MarkVTableUsed(CurrentLocation, ClassDecl);
12813
12814 // Add a context note for diagnostics produced after this point.
12815 Scope.addContextNote(CurrentLocation);
12816
12817 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12818 MoveConstructor->setInvalidDecl();
12819 } else {
12820 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12821 ? MoveConstructor->getEndLoc()
12822 : MoveConstructor->getLocation();
12823 Sema::CompoundScopeRAII CompoundScope(*this);
12824 MoveConstructor->setBody(ActOnCompoundStmt(
12825 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12826 MoveConstructor->markUsed(Context);
12827 }
12828
12829 if (ASTMutationListener *L = getASTMutationListener()) {
12830 L->CompletedImplicitDefinition(MoveConstructor);
12831 }
12832}
12833
12834bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12835 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12836}
12837
12838void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12839 SourceLocation CurrentLocation,
12840 CXXConversionDecl *Conv) {
12841 SynthesizedFunctionScope Scope(*this, Conv);
12842 assert(!Conv->getReturnType()->isUndeducedType());
12843
12844 CXXRecordDecl *Lambda = Conv->getParent();
12845 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12846 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12847
12848 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12849 CallOp = InstantiateFunctionDeclaration(
12850 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12851 if (!CallOp)
12852 return;
12853
12854 Invoker = InstantiateFunctionDeclaration(
12855 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12856 if (!Invoker)
12857 return;
12858 }
12859
12860 if (CallOp->isInvalidDecl())
12861 return;
12862
12863 // Mark the call operator referenced (and add to pending instantiations
12864 // if necessary).
12865 // For both the conversion and static-invoker template specializations
12866 // we construct their body's in this function, so no need to add them
12867 // to the PendingInstantiations.
12868 MarkFunctionReferenced(CurrentLocation, CallOp);
12869
12870 // Fill in the __invoke function with a dummy implementation. IR generation
12871 // will fill in the actual details. Update its type in case it contained
12872 // an 'auto'.
12873 Invoker->markUsed(Context);
12874 Invoker->setReferenced();
12875 Invoker->setType(Conv->getReturnType()->getPointeeType());
12876 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12877
12878 // Construct the body of the conversion function { return __invoke; }.
12879 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12880 VK_LValue, Conv->getLocation());
12881 assert(FunctionRef && "Can't refer to __invoke function?");
12882 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12883 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12884 Conv->getLocation()));
12885 Conv->markUsed(Context);
12886 Conv->setReferenced();
12887
12888 if (ASTMutationListener *L = getASTMutationListener()) {
12889 L->CompletedImplicitDefinition(Conv);
12890 L->CompletedImplicitDefinition(Invoker);
12891 }
12892}
12893
12894
12895
12896void Sema::DefineImplicitLambdaToBlockPointerConversion(
12897 SourceLocation CurrentLocation,
12898 CXXConversionDecl *Conv)
12899{
12900 assert(!Conv->getParent()->isGenericLambda());
12901
12902 SynthesizedFunctionScope Scope(*this, Conv);
12903
12904 // Copy-initialize the lambda object as needed to capture it.
12905 Expr *This = ActOnCXXThis(CurrentLocation).get();
12906 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12907
12908 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12909 Conv->getLocation(),
12910 Conv, DerefThis);
12911
12912 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12913 // behavior. Note that only the general conversion function does this
12914 // (since it's unusable otherwise); in the case where we inline the
12915 // block literal, it has block literal lifetime semantics.
12916 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12917 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12918 CK_CopyAndAutoreleaseBlockObject,
12919 BuildBlock.get(), nullptr, VK_RValue);
12920
12921 if (BuildBlock.isInvalid()) {
12922 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12923 Conv->setInvalidDecl();
12924 return;
12925 }
12926
12927 // Create the return statement that returns the block from the conversion
12928 // function.
12929 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12930 if (Return.isInvalid()) {
12931 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12932 Conv->setInvalidDecl();
12933 return;
12934 }
12935
12936 // Set the body of the conversion function.
12937 Stmt *ReturnS = Return.get();
12938 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12939 Conv->getLocation()));
12940 Conv->markUsed(Context);
12941
12942 // We're done; notify the mutation listener, if any.
12943 if (ASTMutationListener *L = getASTMutationListener()) {
12944 L->CompletedImplicitDefinition(Conv);
12945 }
12946}
12947
12948/// Determine whether the given list arguments contains exactly one
12949/// "real" (non-default) argument.
12950static bool hasOneRealArgument(MultiExprArg Args) {
12951 switch (Args.size()) {
12952 case 0:
12953 return false;
12954
12955 default:
12956 if (!Args[1]->isDefaultArgument())
12957 return false;
12958
12959 LLVM_FALLTHROUGH;
12960 case 1:
12961 return !Args[0]->isDefaultArgument();
12962 }
12963
12964 return false;
12965}
12966
12967ExprResult
12968Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12969 NamedDecl *FoundDecl,
12970 CXXConstructorDecl *Constructor,
12971 MultiExprArg ExprArgs,
12972 bool HadMultipleCandidates,
12973 bool IsListInitialization,
12974 bool IsStdInitListInitialization,
12975 bool RequiresZeroInit,
12976 unsigned ConstructKind,
12977 SourceRange ParenRange) {
12978 bool Elidable = false;
12979
12980 // C++0x [class.copy]p34:
12981 // When certain criteria are met, an implementation is allowed to
12982 // omit the copy/move construction of a class object, even if the
12983 // copy/move constructor and/or destructor for the object have
12984 // side effects. [...]
12985 // - when a temporary class object that has not been bound to a
12986 // reference (12.2) would be copied/moved to a class object
12987 // with the same cv-unqualified type, the copy/move operation
12988 // can be omitted by constructing the temporary object
12989 // directly into the target of the omitted copy/move
12990 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12991 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12992 Expr *SubExpr = ExprArgs[0];
12993 Elidable = SubExpr->isTemporaryObject(
12994 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12995 }
12996
12997 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12998 FoundDecl, Constructor,
12999 Elidable, ExprArgs, HadMultipleCandidates,
13000 IsListInitialization,
13001 IsStdInitListInitialization, RequiresZeroInit,
13002 ConstructKind, ParenRange);
13003}
13004
13005ExprResult
13006Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13007 NamedDecl *FoundDecl,
13008 CXXConstructorDecl *Constructor,
13009 bool Elidable,
13010 MultiExprArg ExprArgs,
13011 bool HadMultipleCandidates,
13012 bool IsListInitialization,
13013 bool IsStdInitListInitialization,
13014 bool RequiresZeroInit,
13015 unsigned ConstructKind,
13016 SourceRange ParenRange) {
13017 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13018 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13019 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13020 return ExprError();
13021 }
13022
13023 return BuildCXXConstructExpr(
13024 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13025 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13026 RequiresZeroInit, ConstructKind, ParenRange);
13027}
13028
13029/// BuildCXXConstructExpr - Creates a complete call to a constructor,
13030/// including handling of its default argument expressions.
13031ExprResult
13032Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13033 CXXConstructorDecl *Constructor,
13034 bool Elidable,
13035 MultiExprArg ExprArgs,
13036 bool HadMultipleCandidates,
13037 bool IsListInitialization,
13038 bool IsStdInitListInitialization,
13039 bool RequiresZeroInit,
13040 unsigned ConstructKind,
13041 SourceRange ParenRange) {
13042 assert(declaresSameEntity(
13043 Constructor->getParent(),
13044 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13045 "given constructor for wrong type");
13046 MarkFunctionReferenced(ConstructLoc, Constructor);
13047 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13048 return ExprError();
13049
13050 return CXXConstructExpr::Create(
13051 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13052 ExprArgs, HadMultipleCandidates, IsListInitialization,
13053 IsStdInitListInitialization, RequiresZeroInit,
13054 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13055 ParenRange);
13056}
13057
13058ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13059 assert(Field->hasInClassInitializer());
13060
13061 // If we already have the in-class initializer nothing needs to be done.
13062 if (Field->getInClassInitializer())
13063 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13064
13065 // If we might have already tried and failed to instantiate, don't try again.
13066 if (Field->isInvalidDecl())
13067 return ExprError();
13068
13069 // Maybe we haven't instantiated the in-class initializer. Go check the
13070 // pattern FieldDecl to see if it has one.
13071 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13072
13073 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13074 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13075 DeclContext::lookup_result Lookup =
13076 ClassPattern->lookup(Field->getDeclName());
13077
13078 // Lookup can return at most two results: the pattern for the field, or the
13079 // injected class name of the parent record. No other member can have the
13080 // same name as the field.
13081 // In modules mode, lookup can return multiple results (coming from
13082 // different modules).
13083 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13084 "more than two lookup results for field name");
13085 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13086 if (!Pattern) {
13087 assert(isa<CXXRecordDecl>(Lookup[0]) &&
13088 "cannot have other non-field member with same name");
13089 for (auto L : Lookup)
13090 if (isa<FieldDecl>(L)) {
13091 Pattern = cast<FieldDecl>(L);
13092 break;
13093 }
13094 assert(Pattern && "We must have set the Pattern!");
13095 }
13096
13097 if (!Pattern->hasInClassInitializer() ||
13098 InstantiateInClassInitializer(Loc, Field, Pattern,
13099 getTemplateInstantiationArgs(Field))) {
13100 // Don't diagnose this again.
13101 Field->setInvalidDecl();
13102 return ExprError();
13103 }
13104 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13105 }
13106
13107 // DR1351:
13108 // If the brace-or-equal-initializer of a non-static data member
13109 // invokes a defaulted default constructor of its class or of an
13110 // enclosing class in a potentially evaluated subexpression, the
13111 // program is ill-formed.
13112 //
13113 // This resolution is unworkable: the exception specification of the
13114 // default constructor can be needed in an unevaluated context, in
13115 // particular, in the operand of a noexcept-expression, and we can be
13116 // unable to compute an exception specification for an enclosed class.
13117 //
13118 // Any attempt to resolve the exception specification of a defaulted default
13119 // constructor before the initializer is lexically complete will ultimately
13120 // come here at which point we can diagnose it.
13121 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13122 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13123 << OutermostClass << Field;
13124 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13125 // Recover by marking the field invalid, unless we're in a SFINAE context.
13126 if (!isSFINAEContext())
13127 Field->setInvalidDecl();
13128 return ExprError();
13129}
13130
13131void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13132 if (VD->isInvalidDecl()) return;
13133
13134 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13135 if (ClassDecl->isInvalidDecl()) return;
13136 if (ClassDecl->hasIrrelevantDestructor()) return;
13137 if (ClassDecl->isDependentContext()) return;
13138
13139 if (VD->isNoDestroy(getASTContext()))
13140 return;
13141
13142 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13143
13144 // If this is an array, we'll require the destructor during initialization, so
13145 // we can skip over this. We still want to emit exit-time destructor warnings
13146 // though.
13147 if (!VD->getType()->isArrayType()) {
13148 MarkFunctionReferenced(VD->getLocation(), Destructor);
13149 CheckDestructorAccess(VD->getLocation(), Destructor,
13150 PDiag(diag::err_access_dtor_var)
13151 << VD->getDeclName() << VD->getType());
13152 DiagnoseUseOfDecl(Destructor, VD->getLocation());
13153 }
13154
13155 if (Destructor->isTrivial()) return;
13156 if (!VD->hasGlobalStorage()) return;
13157
13158 // Emit warning for non-trivial dtor in global scope (a real global,
13159 // class-static, function-static).
13160 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13161
13162 // TODO: this should be re-enabled for static locals by !CXAAtExit
13163 if (!VD->isStaticLocal())
13164 Diag(VD->getLocation(), diag::warn_global_destructor);
13165}
13166
13167/// Given a constructor and the set of arguments provided for the
13168/// constructor, convert the arguments and add any required default arguments
13169/// to form a proper call to this constructor.
13170///
13171/// \returns true if an error occurred, false otherwise.
13172bool
13173Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13174 MultiExprArg ArgsPtr,
13175 SourceLocation Loc,
13176 SmallVectorImpl<Expr*> &ConvertedArgs,
13177 bool AllowExplicit,
13178 bool IsListInitialization) {
13179 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13180 unsigned NumArgs = ArgsPtr.size();
13181 Expr **Args = ArgsPtr.data();
13182
13183 const FunctionProtoType *Proto
13184 = Constructor->getType()->getAs<FunctionProtoType>();
13185 assert(Proto && "Constructor without a prototype?");
13186 unsigned NumParams = Proto->getNumParams();
13187
13188 // If too few arguments are available, we'll fill in the rest with defaults.
13189 if (NumArgs < NumParams)
13190 ConvertedArgs.reserve(NumParams);
13191 else
13192 ConvertedArgs.reserve(NumArgs);
13193
13194 VariadicCallType CallType =
13195 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13196 SmallVector<Expr *, 8> AllArgs;
13197 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13198 Proto, 0,
13199 llvm::makeArrayRef(Args, NumArgs),
13200 AllArgs,
13201 CallType, AllowExplicit,
13202 IsListInitialization);
13203 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13204
13205 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13206
13207 CheckConstructorCall(Constructor,
13208 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13209 Proto, Loc);
13210
13211 return Invalid;
13212}
13213
13214static inline bool
13215CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13216 const FunctionDecl *FnDecl) {
13217 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13218 if (isa<NamespaceDecl>(DC)) {
13219 return SemaRef.Diag(FnDecl->getLocation(),
13220 diag::err_operator_new_delete_declared_in_namespace)
13221 << FnDecl->getDeclName();
13222 }
13223
13224 if (isa<TranslationUnitDecl>(DC) &&
13225 FnDecl->getStorageClass() == SC_Static) {
13226 return SemaRef.Diag(FnDecl->getLocation(),
13227 diag::err_operator_new_delete_declared_static)
13228 << FnDecl->getDeclName();
13229 }
13230
13231 return false;
13232}
13233
13234static QualType
13235RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13236 QualType QTy = PtrTy->getPointeeType();
13237 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13238 return SemaRef.Context.getPointerType(QTy);
13239}
13240
13241static inline bool
13242CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13243 CanQualType ExpectedResultType,
13244 CanQualType ExpectedFirstParamType,
13245 unsigned DependentParamTypeDiag,
13246 unsigned InvalidParamTypeDiag) {
13247 QualType ResultType =
13248 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13249
13250 // Check that the result type is not dependent.
13251 if (ResultType->isDependentType())
13252 return SemaRef.Diag(FnDecl->getLocation(),
13253 diag::err_operator_new_delete_dependent_result_type)
13254 << FnDecl->getDeclName() << ExpectedResultType;
13255
13256 // OpenCL C++: the operator is valid on any address space.
13257 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13258 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13259 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13260 }
13261 }
13262
13263 // Check that the result type is what we expect.
13264 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13265 return SemaRef.Diag(FnDecl->getLocation(),
13266 diag::err_operator_new_delete_invalid_result_type)
13267 << FnDecl->getDeclName() << ExpectedResultType;
13268
13269 // A function template must have at least 2 parameters.
13270 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13271 return SemaRef.Diag(FnDecl->getLocation(),
13272 diag::err_operator_new_delete_template_too_few_parameters)
13273 << FnDecl->getDeclName();
13274
13275 // The function decl must have at least 1 parameter.
13276 if (FnDecl->getNumParams() == 0)
13277 return SemaRef.Diag(FnDecl->getLocation(),
13278 diag::err_operator_new_delete_too_few_parameters)
13279 << FnDecl->getDeclName();
13280
13281 // Check the first parameter type is not dependent.
13282 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13283 if (FirstParamType->isDependentType())
13284 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13285 << FnDecl->getDeclName() << ExpectedFirstParamType;
13286
13287 // Check that the first parameter type is what we expect.
13288 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13289 // OpenCL C++: the operator is valid on any address space.
13290 if (auto *PtrTy =
13291 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13292 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13293 }
13294 }
13295 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13296 ExpectedFirstParamType)
13297 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13298 << FnDecl->getDeclName() << ExpectedFirstParamType;
13299
13300 return false;
13301}
13302
13303static bool
13304CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13305 // C++ [basic.stc.dynamic.allocation]p1:
13306 // A program is ill-formed if an allocation function is declared in a
13307 // namespace scope other than global scope or declared static in global
13308 // scope.
13309 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13310 return true;
13311
13312 CanQualType SizeTy =
13313 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13314
13315 // C++ [basic.stc.dynamic.allocation]p1:
13316 // The return type shall be void*. The first parameter shall have type
13317 // std::size_t.
13318 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13319 SizeTy,
13320 diag::err_operator_new_dependent_param_type,
13321 diag::err_operator_new_param_type))
13322 return true;
13323
13324 // C++ [basic.stc.dynamic.allocation]p1:
13325 // The first parameter shall not have an associated default argument.
13326 if (FnDecl->getParamDecl(0)->hasDefaultArg())
13327 return SemaRef.Diag(FnDecl->getLocation(),
13328 diag::err_operator_new_default_arg)
13329 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13330
13331 return false;
13332}
13333
13334static bool
13335CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13336 // C++ [basic.stc.dynamic.deallocation]p1:
13337 // A program is ill-formed if deallocation functions are declared in a
13338 // namespace scope other than global scope or declared static in global
13339 // scope.
13340 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13341 return true;
13342
13343 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13344
13345 // C++ P0722:
13346 // Within a class C, the first parameter of a destroying operator delete
13347 // shall be of type C *. The first parameter of any other deallocation
13348 // function shall be of type void *.
13349 CanQualType ExpectedFirstParamType =
13350 MD && MD->isDestroyingOperatorDelete()
13351 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13352 SemaRef.Context.getRecordType(MD->getParent())))
13353 : SemaRef.Context.VoidPtrTy;
13354
13355 // C++ [basic.stc.dynamic.deallocation]p2:
13356 // Each deallocation function shall return void
13357 if (CheckOperatorNewDeleteTypes(
13358 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13359 diag::err_operator_delete_dependent_param_type,
13360 diag::err_operator_delete_param_type))
13361 return true;
13362
13363 // C++ P0722:
13364 // A destroying operator delete shall be a usual deallocation function.
13365 if (MD && !MD->getParent()->isDependentContext() &&
13366 MD->isDestroyingOperatorDelete() &&
13367 !SemaRef.isUsualDeallocationFunction(MD)) {
13368 SemaRef.Diag(MD->getLocation(),
13369 diag::err_destroying_operator_delete_not_usual);
13370 return true;
13371 }
13372
13373 return false;
13374}
13375
13376/// CheckOverloadedOperatorDeclaration - Check whether the declaration
13377/// of this overloaded operator is well-formed. If so, returns false;
13378/// otherwise, emits appropriate diagnostics and returns true.
13379bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13380 assert(FnDecl && FnDecl->isOverloadedOperator() &&
13381 "Expected an overloaded operator declaration");
13382
13383 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13384
13385 // C++ [over.oper]p5:
13386 // The allocation and deallocation functions, operator new,
13387 // operator new[], operator delete and operator delete[], are
13388 // described completely in 3.7.3. The attributes and restrictions
13389 // found in the rest of this subclause do not apply to them unless
13390 // explicitly stated in 3.7.3.
13391 if (Op == OO_Delete || Op == OO_Array_Delete)
13392 return CheckOperatorDeleteDeclaration(*this, FnDecl);
13393
13394 if (Op == OO_New || Op == OO_Array_New)
13395 return CheckOperatorNewDeclaration(*this, FnDecl);
13396
13397 // C++ [over.oper]p6:
13398 // An operator function shall either be a non-static member
13399 // function or be a non-member function and have at least one
13400 // parameter whose type is a class, a reference to a class, an
13401 // enumeration, or a reference to an enumeration.
13402 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13403 if (MethodDecl->isStatic())
13404 return Diag(FnDecl->getLocation(),
13405 diag::err_operator_overload_static) << FnDecl->getDeclName();
13406 } else {
13407 bool ClassOrEnumParam = false;
13408 for (auto Param : FnDecl->parameters()) {
13409 QualType ParamType = Param->getType().getNonReferenceType();
13410 if (ParamType->isDependentType() || ParamType->isRecordType() ||
13411 ParamType->isEnumeralType()) {
13412 ClassOrEnumParam = true;
13413 break;
13414 }
13415 }
13416
13417 if (!ClassOrEnumParam)
13418 return Diag(FnDecl->getLocation(),
13419 diag::err_operator_overload_needs_class_or_enum)
13420 << FnDecl->getDeclName();
13421 }
13422
13423 // C++ [over.oper]p8:
13424 // An operator function cannot have default arguments (8.3.6),
13425 // except where explicitly stated below.
13426 //
13427 // Only the function-call operator allows default arguments
13428 // (C++ [over.call]p1).
13429 if (Op != OO_Call) {
13430 for (auto Param : FnDecl->parameters()) {
13431 if (Param->hasDefaultArg())
13432 return Diag(Param->getLocation(),
13433 diag::err_operator_overload_default_arg)
13434 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13435 }
13436 }
13437
13438 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13439 { false, false, false }
13440#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13441 , { Unary, Binary, MemberOnly }
13442#include "clang/Basic/OperatorKinds.def"
13443 };
13444
13445 bool CanBeUnaryOperator = OperatorUses[Op][0];
13446 bool CanBeBinaryOperator = OperatorUses[Op][1];
13447 bool MustBeMemberOperator = OperatorUses[Op][2];
13448
13449 // C++ [over.oper]p8:
13450 // [...] Operator functions cannot have more or fewer parameters
13451 // than the number required for the corresponding operator, as
13452 // described in the rest of this subclause.
13453 unsigned NumParams = FnDecl->getNumParams()
13454 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13455 if (Op != OO_Call &&
13456 ((NumParams == 1 && !CanBeUnaryOperator) ||
13457 (NumParams == 2 && !CanBeBinaryOperator) ||
13458 (NumParams < 1) || (NumParams > 2))) {
13459 // We have the wrong number of parameters.
13460 unsigned ErrorKind;
13461 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13462 ErrorKind = 2; // 2 -> unary or binary.
13463 } else if (CanBeUnaryOperator) {
13464 ErrorKind = 0; // 0 -> unary
13465 } else {
13466 assert(CanBeBinaryOperator &&
13467 "All non-call overloaded operators are unary or binary!");
13468 ErrorKind = 1; // 1 -> binary
13469 }
13470
13471 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13472 << FnDecl->getDeclName() << NumParams << ErrorKind;
13473 }
13474
13475 // Overloaded operators other than operator() cannot be variadic.
13476 if (Op != OO_Call &&
13477 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13478 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13479 << FnDecl->getDeclName();
13480 }
13481
13482 // Some operators must be non-static member functions.
13483 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13484 return Diag(FnDecl->getLocation(),
13485 diag::err_operator_overload_must_be_member)
13486 << FnDecl->getDeclName();
13487 }
13488
13489 // C++ [over.inc]p1:
13490 // The user-defined function called operator++ implements the
13491 // prefix and postfix ++ operator. If this function is a member
13492 // function with no parameters, or a non-member function with one
13493 // parameter of class or enumeration type, it defines the prefix
13494 // increment operator ++ for objects of that type. If the function
13495 // is a member function with one parameter (which shall be of type
13496 // int) or a non-member function with two parameters (the second
13497 // of which shall be of type int), it defines the postfix
13498 // increment operator ++ for objects of that type.
13499 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13500 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13501 QualType ParamType = LastParam->getType();
13502
13503 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13504 !ParamType->isDependentType())
13505 return Diag(LastParam->getLocation(),
13506 diag::err_operator_overload_post_incdec_must_be_int)
13507 << LastParam->getType() << (Op == OO_MinusMinus);
13508 }
13509
13510 return false;
13511}
13512
13513static bool
13514checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13515 FunctionTemplateDecl *TpDecl) {
13516 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13517
13518 // Must have one or two template parameters.
13519 if (TemplateParams->size() == 1) {
13520 NonTypeTemplateParmDecl *PmDecl =
13521 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13522
13523 // The template parameter must be a char parameter pack.
13524 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13525 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13526 return false;
13527
13528 } else if (TemplateParams->size() == 2) {
13529 TemplateTypeParmDecl *PmType =
13530 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13531 NonTypeTemplateParmDecl *PmArgs =
13532 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13533
13534 // The second template parameter must be a parameter pack with the
13535 // first template parameter as its type.
13536 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13537 PmArgs->isTemplateParameterPack()) {
13538 const TemplateTypeParmType *TArgs =
13539 PmArgs->getType()->getAs<TemplateTypeParmType>();
13540 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13541 TArgs->getIndex() == PmType->getIndex()) {
13542 if (!SemaRef.inTemplateInstantiation())
13543 SemaRef.Diag(TpDecl->getLocation(),
13544 diag::ext_string_literal_operator_template);
13545 return false;
13546 }
13547 }
13548 }
13549
13550 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13551 diag::err_literal_operator_template)
13552 << TpDecl->getTemplateParameters()->getSourceRange();
13553 return true;
13554}
13555
13556/// CheckLiteralOperatorDeclaration - Check whether the declaration
13557/// of this literal operator function is well-formed. If so, returns
13558/// false; otherwise, emits appropriate diagnostics and returns true.
13559bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13560 if (isa<CXXMethodDecl>(FnDecl)) {
13561 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13562 << FnDecl->getDeclName();
13563 return true;
13564 }
13565
13566 if (FnDecl->isExternC()) {
13567 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13568 if (const LinkageSpecDecl *LSD =
13569 FnDecl->getDeclContext()->getExternCContext())
13570 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13571 return true;
13572 }
13573
13574 // This might be the definition of a literal operator template.
13575 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13576
13577 // This might be a specialization of a literal operator template.
13578 if (!TpDecl)
13579 TpDecl = FnDecl->getPrimaryTemplate();
13580
13581 // template <char...> type operator "" name() and
13582 // template <class T, T...> type operator "" name() are the only valid
13583 // template signatures, and the only valid signatures with no parameters.
13584 if (TpDecl) {
13585 if (FnDecl->param_size() != 0) {
13586 Diag(FnDecl->getLocation(),
13587 diag::err_literal_operator_template_with_params);
13588 return true;
13589 }
13590
13591 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13592 return true;
13593
13594 } else if (FnDecl->param_size() == 1) {
13595 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13596
13597 QualType ParamType = Param->getType().getUnqualifiedType();
13598
13599 // Only unsigned long long int, long double, any character type, and const
13600 // char * are allowed as the only parameters.
13601 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13602 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13603 Context.hasSameType(ParamType, Context.CharTy) ||
13604 Context.hasSameType(ParamType, Context.WideCharTy) ||
13605 Context.hasSameType(ParamType, Context.Char8Ty) ||
13606 Context.hasSameType(ParamType, Context.Char16Ty) ||
13607 Context.hasSameType(ParamType, Context.Char32Ty)) {
13608 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13609 QualType InnerType = Ptr->getPointeeType();
13610
13611 // Pointer parameter must be a const char *.
13612 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13613 Context.CharTy) &&
13614 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13615 Diag(Param->getSourceRange().getBegin(),
13616 diag::err_literal_operator_param)
13617 << ParamType << "'const char *'" << Param->getSourceRange();
13618 return true;
13619 }
13620
13621 } else if (ParamType->isRealFloatingType()) {
13622 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13623 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13624 return true;
13625
13626 } else if (ParamType->isIntegerType()) {
13627 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13628 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13629 return true;
13630
13631 } else {
13632 Diag(Param->getSourceRange().getBegin(),
13633 diag::err_literal_operator_invalid_param)
13634 << ParamType << Param->getSourceRange();
13635 return true;
13636 }
13637
13638 } else if (FnDecl->param_size() == 2) {
13639 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13640
13641 // First, verify that the first parameter is correct.
13642
13643 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13644
13645 // Two parameter function must have a pointer to const as a
13646 // first parameter; let's strip those qualifiers.
13647 const PointerType *PT = FirstParamType->getAs<PointerType>();
13648
13649 if (!PT) {
13650 Diag((*Param)->getSourceRange().getBegin(),
13651 diag::err_literal_operator_param)
13652 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13653 return true;
13654 }
13655
13656 QualType PointeeType = PT->getPointeeType();
13657 // First parameter must be const
13658 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13659 Diag((*Param)->getSourceRange().getBegin(),
13660 diag::err_literal_operator_param)
13661 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13662 return true;
13663 }
13664
13665 QualType InnerType = PointeeType.getUnqualifiedType();
13666 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13667 // const char32_t* are allowed as the first parameter to a two-parameter
13668 // function
13669 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13670 Context.hasSameType(InnerType, Context.WideCharTy) ||
13671 Context.hasSameType(InnerType, Context.Char8Ty) ||
13672 Context.hasSameType(InnerType, Context.Char16Ty) ||
13673 Context.hasSameType(InnerType, Context.Char32Ty))) {
13674 Diag((*Param)->getSourceRange().getBegin(),
13675 diag::err_literal_operator_param)
13676 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13677 return true;
13678 }
13679
13680 // Move on to the second and final parameter.
13681 ++Param;
13682
13683 // The second parameter must be a std::size_t.
13684 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13685 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13686 Diag((*Param)->getSourceRange().getBegin(),
13687 diag::err_literal_operator_param)
13688 << SecondParamType << Context.getSizeType()
13689 << (*Param)->getSourceRange();
13690 return true;
13691 }
13692 } else {
13693 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13694 return true;
13695 }
13696
13697 // Parameters are good.
13698
13699 // A parameter-declaration-clause containing a default argument is not
13700 // equivalent to any of the permitted forms.
13701 for (auto Param : FnDecl->parameters()) {
13702 if (Param->hasDefaultArg()) {
13703 Diag(Param->getDefaultArgRange().getBegin(),
13704 diag::err_literal_operator_default_argument)
13705 << Param->getDefaultArgRange();
13706 break;
13707 }
13708 }
13709
13710 StringRef LiteralName
13711 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13712 if (LiteralName[0] != '_' &&
13713 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13714 // C++11 [usrlit.suffix]p1:
13715 // Literal suffix identifiers that do not start with an underscore
13716 // are reserved for future standardization.
13717 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13718 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13719 }
13720
13721 return false;
13722}
13723
13724/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13725/// linkage specification, including the language and (if present)
13726/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13727/// language string literal. LBraceLoc, if valid, provides the location of
13728/// the '{' brace. Otherwise, this linkage specification does not
13729/// have any braces.
13730Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13731 Expr *LangStr,
13732 SourceLocation LBraceLoc) {
13733 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13734 if (!Lit->isAscii()) {
13735 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13736 << LangStr->getSourceRange();
13737 return nullptr;
13738 }
13739
13740 StringRef Lang = Lit->getString();
13741 LinkageSpecDecl::LanguageIDs Language;
13742 if (Lang == "C")
13743 Language = LinkageSpecDecl::lang_c;
13744 else if (Lang == "C++")
13745 Language = LinkageSpecDecl::lang_cxx;
13746 else {
13747 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13748 << LangStr->getSourceRange();
13749 return nullptr;
13750 }
13751
13752 // FIXME: Add all the various semantics of linkage specifications
13753
13754 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13755 LangStr->getExprLoc(), Language,
13756 LBraceLoc.isValid());
13757 CurContext->addDecl(D);
13758 PushDeclContext(S, D);
13759 return D;
13760}
13761
13762/// ActOnFinishLinkageSpecification - Complete the definition of
13763/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13764/// valid, it's the position of the closing '}' brace in a linkage
13765/// specification that uses braces.
13766Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13767 Decl *LinkageSpec,
13768 SourceLocation RBraceLoc) {
13769 if (RBraceLoc.isValid()) {
13770 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13771 LSDecl->setRBraceLoc(RBraceLoc);
13772 }
13773 PopDeclContext();
13774 return LinkageSpec;
13775}
13776
13777Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13778 const ParsedAttributesView &AttrList,
13779 SourceLocation SemiLoc) {
13780 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13781 // Attribute declarations appertain to empty declaration so we handle
13782 // them here.
13783 ProcessDeclAttributeList(S, ED, AttrList);
13784
13785 CurContext->addDecl(ED);
13786 return ED;
13787}
13788
13789/// Perform semantic analysis for the variable declaration that
13790/// occurs within a C++ catch clause, returning the newly-created
13791/// variable.
13792VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13793 TypeSourceInfo *TInfo,
13794 SourceLocation StartLoc,
13795 SourceLocation Loc,
13796 IdentifierInfo *Name) {
13797 bool Invalid = false;
13798 QualType ExDeclType = TInfo->getType();
13799
13800 // Arrays and functions decay.
13801 if (ExDeclType->isArrayType())
13802 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13803 else if (ExDeclType->isFunctionType())
13804 ExDeclType = Context.getPointerType(ExDeclType);
13805
13806 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13807 // The exception-declaration shall not denote a pointer or reference to an
13808 // incomplete type, other than [cv] void*.
13809 // N2844 forbids rvalue references.
13810 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13811 Diag(Loc, diag::err_catch_rvalue_ref);
13812 Invalid = true;
13813 }
13814
13815 if (ExDeclType->isVariablyModifiedType()) {
13816 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13817 Invalid = true;
13818 }
13819
13820 QualType BaseType = ExDeclType;
13821 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13822 unsigned DK = diag::err_catch_incomplete;
13823 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13824 BaseType = Ptr->getPointeeType();
13825 Mode = 1;
13826 DK = diag::err_catch_incomplete_ptr;
13827 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13828 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13829 BaseType = Ref->getPointeeType();
13830 Mode = 2;
13831 DK = diag::err_catch_incomplete_ref;
13832 }
13833 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13834 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13835 Invalid = true;
13836
13837 if (!Invalid && !ExDeclType->isDependentType() &&
13838 RequireNonAbstractType(Loc, ExDeclType,
13839 diag::err_abstract_type_in_decl,
13840 AbstractVariableType))
13841 Invalid = true;
13842
13843 // Only the non-fragile NeXT runtime currently supports C++ catches
13844 // of ObjC types, and no runtime supports catching ObjC types by value.
13845 if (!Invalid && getLangOpts().ObjC) {
13846 QualType T = ExDeclType;
13847 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13848 T = RT->getPointeeType();
13849
13850 if (T->isObjCObjectType()) {
13851 Diag(Loc, diag::err_objc_object_catch);
13852 Invalid = true;
13853 } else if (T->isObjCObjectPointerType()) {
13854 // FIXME: should this be a test for macosx-fragile specifically?
13855 if (getLangOpts().ObjCRuntime.isFragile())
13856 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13857 }
13858 }
13859
13860 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13861 ExDeclType, TInfo, SC_None);
13862 ExDecl->setExceptionVariable(true);
13863
13864 // In ARC, infer 'retaining' for variables of retainable type.
13865 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13866 Invalid = true;
13867
13868 if (!Invalid && !ExDeclType->isDependentType()) {
13869 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13870 // Insulate this from anything else we might currently be parsing.
13871 EnterExpressionEvaluationContext scope(
13872 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13873
13874 // C++ [except.handle]p16:
13875 // The object declared in an exception-declaration or, if the
13876 // exception-declaration does not specify a name, a temporary (12.2) is
13877 // copy-initialized (8.5) from the exception object. [...]
13878 // The object is destroyed when the handler exits, after the destruction
13879 // of any automatic objects initialized within the handler.
13880 //
13881 // We just pretend to initialize the object with itself, then make sure
13882 // it can be destroyed later.
13883 QualType initType = Context.getExceptionObjectType(ExDeclType);
13884
13885 InitializedEntity entity =
13886 InitializedEntity::InitializeVariable(ExDecl);
13887 InitializationKind initKind =
13888 InitializationKind::CreateCopy(Loc, SourceLocation());
13889
13890 Expr *opaqueValue =
13891 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13892 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13893 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13894 if (result.isInvalid())
13895 Invalid = true;
13896 else {
13897 // If the constructor used was non-trivial, set this as the
13898 // "initializer".
13899 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13900 if (!construct->getConstructor()->isTrivial()) {
13901 Expr *init = MaybeCreateExprWithCleanups(construct);
13902 ExDecl->setInit(init);
13903 }
13904
13905 // And make sure it's destructable.
13906 FinalizeVarWithDestructor(ExDecl, recordType);
13907 }
13908 }
13909 }
13910
13911 if (Invalid)
13912 ExDecl->setInvalidDecl();
13913
13914 return ExDecl;
13915}
13916
13917/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13918/// handler.
13919Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13920 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13921 bool Invalid = D.isInvalidType();
13922
13923 // Check for unexpanded parameter packs.
13924 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13925 UPPC_ExceptionType)) {
13926 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13927 D.getIdentifierLoc());
13928 Invalid = true;
13929 }
13930
13931 IdentifierInfo *II = D.getIdentifier();
13932 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13933 LookupOrdinaryName,
13934 ForVisibleRedeclaration)) {
13935 // The scope should be freshly made just for us. There is just no way
13936 // it contains any previous declaration, except for function parameters in
13937 // a function-try-block's catch statement.
13938 assert(!S->isDeclScope(PrevDecl));
13939 if (isDeclInScope(PrevDecl, CurContext, S)) {
13940 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13941 << D.getIdentifier();
13942 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13943 Invalid = true;
13944 } else if (PrevDecl->isTemplateParameter())
13945 // Maybe we will complain about the shadowed template parameter.
13946 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13947 }
13948
13949 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13950 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13951 << D.getCXXScopeSpec().getRange();
13952 Invalid = true;
13953 }
13954
13955 VarDecl *ExDecl = BuildExceptionDeclaration(
13956 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13957 if (Invalid)
13958 ExDecl->setInvalidDecl();
13959
13960 // Add the exception declaration into this scope.
13961 if (II)
13962 PushOnScopeChains(ExDecl, S);
13963 else
13964 CurContext->addDecl(ExDecl);
13965
13966 ProcessDeclAttributes(S, ExDecl, D);
13967 return ExDecl;
13968}
13969
13970Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13971 Expr *AssertExpr,
13972 Expr *AssertMessageExpr,
13973 SourceLocation RParenLoc) {
13974 StringLiteral *AssertMessage =
13975 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13976
13977 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13978 return nullptr;
13979
13980 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13981 AssertMessage, RParenLoc, false);
13982}
13983
13984Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13985 Expr *AssertExpr,
13986 StringLiteral *AssertMessage,
13987 SourceLocation RParenLoc,
13988 bool Failed) {
13989 assert(AssertExpr != nullptr && "Expected non-null condition");
13990 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13991 !Failed) {
13992 // In a static_assert-declaration, the constant-expression shall be a
13993 // constant expression that can be contextually converted to bool.
13994 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13995 if (Converted.isInvalid())
13996 Failed = true;
13997 else
13998 Converted = ConstantExpr::Create(Context, Converted.get());
13999
14000 llvm::APSInt Cond;
14001 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14002 diag::err_static_assert_expression_is_not_constant,
14003 /*AllowFold=*/false).isInvalid())
14004 Failed = true;
14005
14006 if (!Failed && !Cond) {
14007 SmallString<256> MsgBuffer;
14008 llvm::raw_svector_ostream Msg(MsgBuffer);
14009 if (AssertMessage)
14010 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14011
14012 Expr *InnerCond = nullptr;
14013 std::string InnerCondDescription;
14014 std::tie(InnerCond, InnerCondDescription) =
14015 findFailedBooleanCondition(Converted.get());
14016 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14017 && !isa<IntegerLiteral>(InnerCond)) {
14018 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14019 << InnerCondDescription << !AssertMessage
14020 << Msg.str() << InnerCond->getSourceRange();
14021 } else {
14022 Diag(StaticAssertLoc, diag::err_static_assert_failed)
14023 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14024 }
14025 Failed = true;
14026 }
14027 }
14028
14029 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14030 /*DiscardedValue*/false,
14031 /*IsConstexpr*/true);
14032 if (FullAssertExpr.isInvalid())
14033 Failed = true;
14034 else
14035 AssertExpr = FullAssertExpr.get();
14036
14037 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14038 AssertExpr, AssertMessage, RParenLoc,
14039 Failed);
14040
14041 CurContext->addDecl(Decl);
14042 return Decl;
14043}
14044
14045/// Perform semantic analysis of the given friend type declaration.
14046///
14047/// \returns A friend declaration that.
14048FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14049 SourceLocation FriendLoc,
14050 TypeSourceInfo *TSInfo) {
14051 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14052
14053 QualType T = TSInfo->getType();
14054 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14055
14056 // C++03 [class.friend]p2:
14057 // An elaborated-type-specifier shall be used in a friend declaration
14058 // for a class.*
14059 //
14060 // * The class-key of the elaborated-type-specifier is required.
14061 if (!CodeSynthesisContexts.empty()) {
14062 // Do not complain about the form of friend template types during any kind
14063 // of code synthesis. For template instantiation, we will have complained
14064 // when the template was defined.
14065 } else {
14066 if (!T->isElaboratedTypeSpecifier()) {
14067 // If we evaluated the type to a record type, suggest putting
14068 // a tag in front.
14069 if (const RecordType *RT = T->getAs<RecordType>()) {
14070 RecordDecl *RD = RT->getDecl();
14071
14072 SmallString<16> InsertionText(" ");
14073 InsertionText += RD->getKindName();
14074
14075 Diag(TypeRange.getBegin(),
14076 getLangOpts().CPlusPlus11 ?
14077 diag::warn_cxx98_compat_unelaborated_friend_type :
14078 diag::ext_unelaborated_friend_type)
14079 << (unsigned) RD->getTagKind()
14080 << T
14081 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14082 InsertionText);
14083 } else {
14084 Diag(FriendLoc,
14085 getLangOpts().CPlusPlus11 ?
14086 diag::warn_cxx98_compat_nonclass_type_friend :
14087 diag::ext_nonclass_type_friend)
14088 << T
14089 << TypeRange;
14090 }
14091 } else if (T->getAs<EnumType>()) {
14092 Diag(FriendLoc,
14093 getLangOpts().CPlusPlus11 ?
14094 diag::warn_cxx98_compat_enum_friend :
14095 diag::ext_enum_friend)
14096 << T
14097 << TypeRange;
14098 }
14099
14100 // C++11 [class.friend]p3:
14101 // A friend declaration that does not declare a function shall have one
14102 // of the following forms:
14103 // friend elaborated-type-specifier ;
14104 // friend simple-type-specifier ;
14105 // friend typename-specifier ;
14106 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14107 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14108 }
14109
14110 // If the type specifier in a friend declaration designates a (possibly
14111 // cv-qualified) class type, that class is declared as a friend; otherwise,
14112 // the friend declaration is ignored.
14113 return FriendDecl::Create(Context, CurContext,
14114 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14115 FriendLoc);
14116}
14117
14118/// Handle a friend tag declaration where the scope specifier was
14119/// templated.
14120Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14121 unsigned TagSpec, SourceLocation TagLoc,
14122 CXXScopeSpec &SS, IdentifierInfo *Name,
14123 SourceLocation NameLoc,
14124 const ParsedAttributesView &Attr,
14125 MultiTemplateParamsArg TempParamLists) {
14126 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14127
14128 bool IsMemberSpecialization = false;
14129 bool Invalid = false;
14130
14131 if (TemplateParameterList *TemplateParams =
14132 MatchTemplateParametersToScopeSpecifier(
14133 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14134 IsMemberSpecialization, Invalid)) {
14135 if (TemplateParams->size() > 0) {
14136 // This is a declaration of a class template.
14137 if (Invalid)
14138 return nullptr;
14139
14140 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14141 NameLoc, Attr, TemplateParams, AS_public,
14142 /*ModulePrivateLoc=*/SourceLocation(),
14143 FriendLoc, TempParamLists.size() - 1,
14144 TempParamLists.data()).get();
14145 } else {
14146 // The "template<>" header is extraneous.
14147 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14148 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14149 IsMemberSpecialization = true;
14150 }
14151 }
14152
14153 if (Invalid) return nullptr;
14154
14155 bool isAllExplicitSpecializations = true;
14156 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14157 if (TempParamLists[I]->size()) {
14158 isAllExplicitSpecializations = false;
14159 break;
14160 }
14161 }
14162
14163 // FIXME: don't ignore attributes.
14164
14165 // If it's explicit specializations all the way down, just forget
14166 // about the template header and build an appropriate non-templated
14167 // friend. TODO: for source fidelity, remember the headers.
14168 if (isAllExplicitSpecializations) {
14169 if (SS.isEmpty()) {
14170 bool Owned = false;
14171 bool IsDependent = false;
14172 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14173 Attr, AS_public,
14174 /*ModulePrivateLoc=*/SourceLocation(),
14175 MultiTemplateParamsArg(), Owned, IsDependent,
14176 /*ScopedEnumKWLoc=*/SourceLocation(),
14177 /*ScopedEnumUsesClassTag=*/false,
14178 /*UnderlyingType=*/TypeResult(),
14179 /*IsTypeSpecifier=*/false,
14180 /*IsTemplateParamOrArg=*/false);
14181 }
14182
14183 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14184 ElaboratedTypeKeyword Keyword
14185 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14186 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14187 *Name, NameLoc);
14188 if (T.isNull())
14189 return nullptr;
14190
14191 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14192 if (isa<DependentNameType>(T)) {
14193 DependentNameTypeLoc TL =
14194 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14195 TL.setElaboratedKeywordLoc(TagLoc);
14196 TL.setQualifierLoc(QualifierLoc);
14197 TL.setNameLoc(NameLoc);
14198 } else {
14199 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14200 TL.setElaboratedKeywordLoc(TagLoc);
14201 TL.setQualifierLoc(QualifierLoc);
14202 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14203 }
14204
14205 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14206 TSI, FriendLoc, TempParamLists);
14207 Friend->setAccess(AS_public);
14208 CurContext->addDecl(Friend);
14209 return Friend;
14210 }
14211
14212 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14213
14214
14215
14216 // Handle the case of a templated-scope friend class. e.g.
14217 // template <class T> class A<T>::B;
14218 // FIXME: we don't support these right now.
14219 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14220 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14221 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14222 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14223 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14224 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14225 TL.setElaboratedKeywordLoc(TagLoc);
14226 TL.setQualifierLoc(SS.getWithLocInContext(Context));
14227 TL.setNameLoc(NameLoc);
14228
14229 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14230 TSI, FriendLoc, TempParamLists);
14231 Friend->setAccess(AS_public);
14232 Friend->setUnsupportedFriend(true);
14233 CurContext->addDecl(Friend);
14234 return Friend;
14235}
14236
14237/// Handle a friend type declaration. This works in tandem with
14238/// ActOnTag.
14239///
14240/// Notes on friend class templates:
14241///
14242/// We generally treat friend class declarations as if they were
14243/// declaring a class. So, for example, the elaborated type specifier
14244/// in a friend declaration is required to obey the restrictions of a
14245/// class-head (i.e. no typedefs in the scope chain), template
14246/// parameters are required to match up with simple template-ids, &c.
14247/// However, unlike when declaring a template specialization, it's
14248/// okay to refer to a template specialization without an empty
14249/// template parameter declaration, e.g.
14250/// friend class A<T>::B<unsigned>;
14251/// We permit this as a special case; if there are any template
14252/// parameters present at all, require proper matching, i.e.
14253/// template <> template \<class T> friend class A<int>::B;
14254Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14255 MultiTemplateParamsArg TempParams) {
14256 SourceLocation Loc = DS.getBeginLoc();
14257
14258 assert(DS.isFriendSpecified());
14259 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14260
14261 // C++ [class.friend]p3:
14262 // A friend declaration that does not declare a function shall have one of
14263 // the following forms:
14264 // friend elaborated-type-specifier ;
14265 // friend simple-type-specifier ;
14266 // friend typename-specifier ;
14267 //
14268 // Any declaration with a type qualifier does not have that form. (It's
14269 // legal to specify a qualified type as a friend, you just can't write the
14270 // keywords.)
14271 if (DS.getTypeQualifiers()) {
14272 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14273 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14274 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14275 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14276 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14277 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14278 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14279 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14280 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14281 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14282 }
14283
14284 // Try to convert the decl specifier to a type. This works for
14285 // friend templates because ActOnTag never produces a ClassTemplateDecl
14286 // for a TUK_Friend.
14287 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14288 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14289 QualType T = TSI->getType();
14290 if (TheDeclarator.isInvalidType())
14291 return nullptr;
14292
14293 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14294 return nullptr;
14295
14296 // This is definitely an error in C++98. It's probably meant to
14297 // be forbidden in C++0x, too, but the specification is just
14298 // poorly written.
14299 //
14300 // The problem is with declarations like the following:
14301 // template <T> friend A<T>::foo;
14302 // where deciding whether a class C is a friend or not now hinges
14303 // on whether there exists an instantiation of A that causes
14304 // 'foo' to equal C. There are restrictions on class-heads
14305 // (which we declare (by fiat) elaborated friend declarations to
14306 // be) that makes this tractable.
14307 //
14308 // FIXME: handle "template <> friend class A<T>;", which
14309 // is possibly well-formed? Who even knows?
14310 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14311 Diag(Loc, diag::err_tagless_friend_type_template)
14312 << DS.getSourceRange();
14313 return nullptr;
14314 }
14315
14316 // C++98 [class.friend]p1: A friend of a class is a function
14317 // or class that is not a member of the class . . .
14318 // This is fixed in DR77, which just barely didn't make the C++03
14319 // deadline. It's also a very silly restriction that seriously
14320 // affects inner classes and which nobody else seems to implement;
14321 // thus we never diagnose it, not even in -pedantic.
14322 //
14323 // But note that we could warn about it: it's always useless to
14324 // friend one of your own members (it's not, however, worthless to
14325 // friend a member of an arbitrary specialization of your template).
14326
14327 Decl *D;
14328 if (!TempParams.empty())
14329 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14330 TempParams,
14331 TSI,
14332 DS.getFriendSpecLoc());
14333 else
14334 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14335
14336 if (!D)
14337 return nullptr;
14338
14339 D->setAccess(AS_public);
14340 CurContext->addDecl(D);
14341
14342 return D;
14343}
14344
14345NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14346 MultiTemplateParamsArg TemplateParams) {
14347 const DeclSpec &DS = D.getDeclSpec();
14348
14349 assert(DS.isFriendSpecified());
14350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14351
14352 SourceLocation Loc = D.getIdentifierLoc();
14353 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14354
14355 // C++ [class.friend]p1
14356 // A friend of a class is a function or class....
14357 // Note that this sees through typedefs, which is intended.
14358 // It *doesn't* see through dependent types, which is correct
14359 // according to [temp.arg.type]p3:
14360 // If a declaration acquires a function type through a
14361 // type dependent on a template-parameter and this causes
14362 // a declaration that does not use the syntactic form of a
14363 // function declarator to have a function type, the program
14364 // is ill-formed.
14365 if (!TInfo->getType()->isFunctionType()) {
14366 Diag(Loc, diag::err_unexpected_friend);
14367
14368 // It might be worthwhile to try to recover by creating an
14369 // appropriate declaration.
14370 return nullptr;
14371 }
14372
14373 // C++ [namespace.memdef]p3
14374 // - If a friend declaration in a non-local class first declares a
14375 // class or function, the friend class or function is a member
14376 // of the innermost enclosing namespace.
14377 // - The name of the friend is not found by simple name lookup
14378 // until a matching declaration is provided in that namespace
14379 // scope (either before or after the class declaration granting
14380 // friendship).
14381 // - If a friend function is called, its name may be found by the
14382 // name lookup that considers functions from namespaces and
14383 // classes associated with the types of the function arguments.
14384 // - When looking for a prior declaration of a class or a function
14385 // declared as a friend, scopes outside the innermost enclosing
14386 // namespace scope are not considered.
14387
14388 CXXScopeSpec &SS = D.getCXXScopeSpec();
14389 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14390 assert(NameInfo.getName());
14391
14392 // Check for unexpanded parameter packs.
14393 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14394 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14395 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14396 return nullptr;
14397
14398 // The context we found the declaration in, or in which we should
14399 // create the declaration.
14400 DeclContext *DC;
14401 Scope *DCScope = S;
14402 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14403 ForExternalRedeclaration);
14404
14405 // There are five cases here.
14406 // - There's no scope specifier and we're in a local class. Only look
14407 // for functions declared in the immediately-enclosing block scope.
14408 // We recover from invalid scope qualifiers as if they just weren't there.
14409 FunctionDecl *FunctionContainingLocalClass = nullptr;
14410 if ((SS.isInvalid() || !SS.isSet()) &&
14411 (FunctionContainingLocalClass =
14412 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14413 // C++11 [class.friend]p11:
14414 // If a friend declaration appears in a local class and the name
14415 // specified is an unqualified name, a prior declaration is
14416 // looked up without considering scopes that are outside the
14417 // innermost enclosing non-class scope. For a friend function
14418 // declaration, if there is no prior declaration, the program is
14419 // ill-formed.
14420
14421 // Find the innermost enclosing non-class scope. This is the block
14422 // scope containing the local class definition (or for a nested class,
14423 // the outer local class).
14424 DCScope = S->getFnParent();
14425
14426 // Look up the function name in the scope.
14427 Previous.clear(LookupLocalFriendName);
14428 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14429
14430 if (!Previous.empty()) {
14431 // All possible previous declarations must have the same context:
14432 // either they were declared at block scope or they are members of
14433 // one of the enclosing local classes.
14434 DC = Previous.getRepresentativeDecl()->getDeclContext();
14435 } else {
14436 // This is ill-formed, but provide the context that we would have
14437 // declared the function in, if we were permitted to, for error recovery.
14438 DC = FunctionContainingLocalClass;
14439 }
14440 adjustContextForLocalExternDecl(DC);
14441
14442 // C++ [class.friend]p6:
14443 // A function can be defined in a friend declaration of a class if and
14444 // only if the class is a non-local class (9.8), the function name is
14445 // unqualified, and the function has namespace scope.
14446 if (D.isFunctionDefinition()) {
14447 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14448 }
14449
14450 // - There's no scope specifier, in which case we just go to the
14451 // appropriate scope and look for a function or function template
14452 // there as appropriate.
14453 } else if (SS.isInvalid() || !SS.isSet()) {
14454 // C++11 [namespace.memdef]p3:
14455 // If the name in a friend declaration is neither qualified nor
14456 // a template-id and the declaration is a function or an
14457 // elaborated-type-specifier, the lookup to determine whether
14458 // the entity has been previously declared shall not consider
14459 // any scopes outside the innermost enclosing namespace.
14460 bool isTemplateId =
14461 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14462
14463 // Find the appropriate context according to the above.
14464 DC = CurContext;
14465
14466 // Skip class contexts. If someone can cite chapter and verse
14467 // for this behavior, that would be nice --- it's what GCC and
14468 // EDG do, and it seems like a reasonable intent, but the spec
14469 // really only says that checks for unqualified existing
14470 // declarations should stop at the nearest enclosing namespace,
14471 // not that they should only consider the nearest enclosing
14472 // namespace.
14473 while (DC->isRecord())
14474 DC = DC->getParent();
14475
14476 DeclContext *LookupDC = DC;
14477 while (LookupDC->isTransparentContext())
14478 LookupDC = LookupDC->getParent();
14479
14480 while (true) {
14481 LookupQualifiedName(Previous, LookupDC);
14482
14483 if (!Previous.empty()) {
14484 DC = LookupDC;
14485 break;
14486 }
14487
14488 if (isTemplateId) {
14489 if (isa<TranslationUnitDecl>(LookupDC)) break;
14490 } else {
14491 if (LookupDC->isFileContext()) break;
14492 }
14493 LookupDC = LookupDC->getParent();
14494 }
14495
14496 DCScope = getScopeForDeclContext(S, DC);
14497
14498 // - There's a non-dependent scope specifier, in which case we
14499 // compute it and do a previous lookup there for a function
14500 // or function template.
14501 } else if (!SS.getScopeRep()->isDependent()) {
14502 DC = computeDeclContext(SS);
14503 if (!DC) return nullptr;
14504
14505 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14506
14507 LookupQualifiedName(Previous, DC);
14508
14509 // C++ [class.friend]p1: A friend of a class is a function or
14510 // class that is not a member of the class . . .
14511 if (DC->Equals(CurContext))
14512 Diag(DS.getFriendSpecLoc(),
14513 getLangOpts().CPlusPlus11 ?
14514 diag::warn_cxx98_compat_friend_is_member :
14515 diag::err_friend_is_member);
14516
14517 if (D.isFunctionDefinition()) {
14518 // C++ [class.friend]p6:
14519 // A function can be defined in a friend declaration of a class if and
14520 // only if the class is a non-local class (9.8), the function name is
14521 // unqualified, and the function has namespace scope.
14522 //
14523 // FIXME: We should only do this if the scope specifier names the
14524 // innermost enclosing namespace; otherwise the fixit changes the
14525 // meaning of the code.
14526 SemaDiagnosticBuilder DB
14527 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14528
14529 DB << SS.getScopeRep();
14530 if (DC->isFileContext())
14531 DB << FixItHint::CreateRemoval(SS.getRange());
14532 SS.clear();
14533 }
14534
14535 // - There's a scope specifier that does not match any template
14536 // parameter lists, in which case we use some arbitrary context,
14537 // create a method or method template, and wait for instantiation.
14538 // - There's a scope specifier that does match some template
14539 // parameter lists, which we don't handle right now.
14540 } else {
14541 if (D.isFunctionDefinition()) {
14542 // C++ [class.friend]p6:
14543 // A function can be defined in a friend declaration of a class if and
14544 // only if the class is a non-local class (9.8), the function name is
14545 // unqualified, and the function has namespace scope.
14546 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14547 << SS.getScopeRep();
14548 }
14549
14550 DC = CurContext;
14551 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14552 }
14553
14554 if (!DC->isRecord()) {
14555 int DiagArg = -1;
14556 switch (D.getName().getKind()) {
14557 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14558 case UnqualifiedIdKind::IK_ConstructorName:
14559 DiagArg = 0;
14560 break;
14561 case UnqualifiedIdKind::IK_DestructorName:
14562 DiagArg = 1;
14563 break;
14564 case UnqualifiedIdKind::IK_ConversionFunctionId:
14565 DiagArg = 2;
14566 break;
14567 case UnqualifiedIdKind::IK_DeductionGuideName:
14568 DiagArg = 3;
14569 break;
14570 case UnqualifiedIdKind::IK_Identifier:
14571 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14572 case UnqualifiedIdKind::IK_LiteralOperatorId:
14573 case UnqualifiedIdKind::IK_OperatorFunctionId:
14574 case UnqualifiedIdKind::IK_TemplateId:
14575 break;
14576 }
14577 // This implies that it has to be an operator or function.
14578 if (DiagArg >= 0) {
14579 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14580 return nullptr;
14581 }
14582 }
14583
14584 // FIXME: This is an egregious hack to cope with cases where the scope stack
14585 // does not contain the declaration context, i.e., in an out-of-line
14586 // definition of a class.
14587 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14588 if (!DCScope) {
14589 FakeDCScope.setEntity(DC);
14590 DCScope = &FakeDCScope;
14591 }
14592
14593 bool AddToScope = true;
14594 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14595 TemplateParams, AddToScope);
14596 if (!ND) return nullptr;
14597
14598 assert(ND->getLexicalDeclContext() == CurContext);
14599
14600 // If we performed typo correction, we might have added a scope specifier
14601 // and changed the decl context.
14602 DC = ND->getDeclContext();
14603
14604 // Add the function declaration to the appropriate lookup tables,
14605 // adjusting the redeclarations list as necessary. We don't
14606 // want to do this yet if the friending class is dependent.
14607 //
14608 // Also update the scope-based lookup if the target context's
14609 // lookup context is in lexical scope.
14610 if (!CurContext->isDependentContext()) {
14611 DC = DC->getRedeclContext();
14612 DC->makeDeclVisibleInContext(ND);
14613 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14614 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14615 }
14616
14617 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14618 D.getIdentifierLoc(), ND,
14619 DS.getFriendSpecLoc());
14620 FrD->setAccess(AS_public);
14621 CurContext->addDecl(FrD);
14622
14623 if (ND->isInvalidDecl()) {
14624 FrD->setInvalidDecl();
14625 } else {
14626 if (DC->isRecord()) CheckFriendAccess(ND);
14627
14628 FunctionDecl *FD;
14629 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14630 FD = FTD->getTemplatedDecl();
14631 else
14632 FD = cast<FunctionDecl>(ND);
14633
14634 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14635 // default argument expression, that declaration shall be a definition
14636 // and shall be the only declaration of the function or function
14637 // template in the translation unit.
14638 if (functionDeclHasDefaultArgument(FD)) {
14639 // We can't look at FD->getPreviousDecl() because it may not have been set
14640 // if we're in a dependent context. If the function is known to be a
14641 // redeclaration, we will have narrowed Previous down to the right decl.
14642 if (D.isRedeclaration()) {
14643 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14644 Diag(Previous.getRepresentativeDecl()->getLocation(),
14645 diag::note_previous_declaration);
14646 } else if (!D.isFunctionDefinition())
14647 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14648 }
14649
14650 // Mark templated-scope function declarations as unsupported.
14651 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14652 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14653 << SS.getScopeRep() << SS.getRange()
14654 << cast<CXXRecordDecl>(CurContext);
14655 FrD->setUnsupportedFriend(true);
14656 }
14657 }
14658
14659 return ND;
14660}
14661
14662void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14663 AdjustDeclIfTemplate(Dcl);
14664
14665 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14666 if (!Fn) {
14667 Diag(DelLoc, diag::err_deleted_non_function);
14668 return;
14669 }
14670
14671 // Deleted function does not have a body.
14672 Fn->setWillHaveBody(false);
14673
14674 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14675 // Don't consider the implicit declaration we generate for explicit
14676 // specializations. FIXME: Do not generate these implicit declarations.
14677 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14678 Prev->getPreviousDecl()) &&
14679 !Prev->isDefined()) {
14680 Diag(DelLoc, diag::err_deleted_decl_not_first);
14681 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14682 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14683 : diag::note_previous_declaration);
14684 }
14685 // If the declaration wasn't the first, we delete the function anyway for
14686 // recovery.
14687 Fn = Fn->getCanonicalDecl();
14688 }
14689
14690 // dllimport/dllexport cannot be deleted.
14691 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14692 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14693 Fn->setInvalidDecl();
14694 }
14695
14696 if (Fn->isDeleted())
14697 return;
14698
14699 // See if we're deleting a function which is already known to override a
14700 // non-deleted virtual function.
14701 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14702 bool IssuedDiagnostic = false;
14703 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14704 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14705 if (!IssuedDiagnostic) {
14706 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14707 IssuedDiagnostic = true;
14708 }
14709 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14710 }
14711 }
14712 // If this function was implicitly deleted because it was defaulted,
14713 // explain why it was deleted.
14714 if (IssuedDiagnostic && MD->isDefaulted())
14715 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14716 /*Diagnose*/true);
14717 }
14718
14719 // C++11 [basic.start.main]p3:
14720 // A program that defines main as deleted [...] is ill-formed.
14721 if (Fn->isMain())
14722 Diag(DelLoc, diag::err_deleted_main);
14723
14724 // C++11 [dcl.fct.def.delete]p4:
14725 // A deleted function is implicitly inline.
14726 Fn->setImplicitlyInline();
14727 Fn->setDeletedAsWritten();
14728}
14729
14730void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14731 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14732
14733 if (MD) {
14734 if (MD->getParent()->isDependentType()) {
14735 MD->setDefaulted();
14736 MD->setExplicitlyDefaulted();
14737 return;
14738 }
14739
14740 CXXSpecialMember Member = getSpecialMember(MD);
14741 if (Member == CXXInvalid) {
14742 if (!MD->isInvalidDecl())
14743 Diag(DefaultLoc, diag::err_default_special_members);
14744 return;
14745 }
14746
14747 MD->setDefaulted();
14748 MD->setExplicitlyDefaulted();
14749
14750 // Unset that we will have a body for this function. We might not,
14751 // if it turns out to be trivial, and we don't need this marking now
14752 // that we've marked it as defaulted.
14753 MD->setWillHaveBody(false);
14754
14755 // If this definition appears within the record, do the checking when
14756 // the record is complete.
14757 const FunctionDecl *Primary = MD;
14758 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14759 // Ask the template instantiation pattern that actually had the
14760 // '= default' on it.
14761 Primary = Pattern;
14762
14763 // If the method was defaulted on its first declaration, we will have
14764 // already performed the checking in CheckCompletedCXXClass. Such a
14765 // declaration doesn't trigger an implicit definition.
14766 if (Primary->getCanonicalDecl()->isDefaulted())
14767 return;
14768
14769 CheckExplicitlyDefaultedSpecialMember(MD);
14770
14771 if (!MD->isInvalidDecl())
14772 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14773 } else {
14774 Diag(DefaultLoc, diag::err_default_special_members);
14775 }
14776}
14777
14778static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14779 for (Stmt *SubStmt : S->children()) {
14780 if (!SubStmt)
14781 continue;
14782 if (isa<ReturnStmt>(SubStmt))
14783 Self.Diag(SubStmt->getBeginLoc(),
14784 diag::err_return_in_constructor_handler);
14785 if (!isa<Expr>(SubStmt))
14786 SearchForReturnInStmt(Self, SubStmt);
14787 }
14788}
14789
14790void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14791 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14792 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14793 SearchForReturnInStmt(*this, Handler);
14794 }
14795}
14796
14797bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14798 const CXXMethodDecl *Old) {
14799 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14800 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14801
14802 if (OldFT->hasExtParameterInfos()) {
14803 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14804 // A parameter of the overriding method should be annotated with noescape
14805 // if the corresponding parameter of the overridden method is annotated.
14806 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14807 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14808 Diag(New->getParamDecl(I)->getLocation(),
14809 diag::warn_overriding_method_missing_noescape);
14810 Diag(Old->getParamDecl(I)->getLocation(),
14811 diag::note_overridden_marked_noescape);
14812 }
14813 }
14814
14815 // Virtual overrides must have the same code_seg.
14816 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14817 const auto *NewCSA = New->getAttr<CodeSegAttr>();
14818 if ((NewCSA || OldCSA) &&
14819 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14820 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14821 Diag(Old->getLocation(), diag::note_previous_declaration);
14822 return true;
14823 }
14824
14825 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14826
14827 // If the calling conventions match, everything is fine
14828 if (NewCC == OldCC)
14829 return false;
14830
14831 // If the calling conventions mismatch because the new function is static,
14832 // suppress the calling convention mismatch error; the error about static
14833 // function override (err_static_overrides_virtual from
14834 // Sema::CheckFunctionDeclaration) is more clear.
14835 if (New->getStorageClass() == SC_Static)
14836 return false;
14837
14838 Diag(New->getLocation(),
14839 diag::err_conflicting_overriding_cc_attributes)
14840 << New->getDeclName() << New->getType() << Old->getType();
14841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14842 return true;
14843}
14844
14845bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14846 const CXXMethodDecl *Old) {
14847 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14848 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14849
14850 if (Context.hasSameType(NewTy, OldTy) ||
14851 NewTy->isDependentType() || OldTy->isDependentType())
14852 return false;
14853
14854 // Check if the return types are covariant
14855 QualType NewClassTy, OldClassTy;
14856
14857 /// Both types must be pointers or references to classes.
14858 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14859 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14860 NewClassTy = NewPT->getPointeeType();
14861 OldClassTy = OldPT->getPointeeType();
14862 }
14863 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14864 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14865 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14866 NewClassTy = NewRT->getPointeeType();
14867 OldClassTy = OldRT->getPointeeType();
14868 }
14869 }
14870 }
14871
14872 // The return types aren't either both pointers or references to a class type.
14873 if (NewClassTy.isNull()) {
14874 Diag(New->getLocation(),
14875 diag::err_different_return_type_for_overriding_virtual_function)
14876 << New->getDeclName() << NewTy << OldTy
14877 << New->getReturnTypeSourceRange();
14878 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14879 << Old->getReturnTypeSourceRange();
14880
14881 return true;
14882 }
14883
14884 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14885 // C++14 [class.virtual]p8:
14886 // If the class type in the covariant return type of D::f differs from
14887 // that of B::f, the class type in the return type of D::f shall be
14888 // complete at the point of declaration of D::f or shall be the class
14889 // type D.
14890 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14891 if (!RT->isBeingDefined() &&
14892 RequireCompleteType(New->getLocation(), NewClassTy,
14893 diag::err_covariant_return_incomplete,
14894 New->getDeclName()))
14895 return true;
14896 }
14897
14898 // Check if the new class derives from the old class.
14899 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14900 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14901 << New->getDeclName() << NewTy << OldTy
14902 << New->getReturnTypeSourceRange();
14903 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14904 << Old->getReturnTypeSourceRange();
14905 return true;
14906 }
14907
14908 // Check if we the conversion from derived to base is valid.
14909 if (CheckDerivedToBaseConversion(
14910 NewClassTy, OldClassTy,
14911 diag::err_covariant_return_inaccessible_base,
14912 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14913 New->getLocation(), New->getReturnTypeSourceRange(),
14914 New->getDeclName(), nullptr)) {
14915 // FIXME: this note won't trigger for delayed access control
14916 // diagnostics, and it's impossible to get an undelayed error
14917 // here from access control during the original parse because
14918 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14919 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14920 << Old->getReturnTypeSourceRange();
14921 return true;
14922 }
14923 }
14924
14925 // The qualifiers of the return types must be the same.
14926 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14927 Diag(New->getLocation(),
14928 diag::err_covariant_return_type_different_qualifications)
14929 << New->getDeclName() << NewTy << OldTy
14930 << New->getReturnTypeSourceRange();
14931 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14932 << Old->getReturnTypeSourceRange();
14933 return true;
14934 }
14935
14936
14937 // The new class type must have the same or less qualifiers as the old type.
14938 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14939 Diag(New->getLocation(),
14940 diag::err_covariant_return_type_class_type_more_qualified)
14941 << New->getDeclName() << NewTy << OldTy
14942 << New->getReturnTypeSourceRange();
14943 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14944 << Old->getReturnTypeSourceRange();
14945 return true;
14946 }
14947
14948 return false;
14949}
14950
14951/// Mark the given method pure.
14952///
14953/// \param Method the method to be marked pure.
14954///
14955/// \param InitRange the source range that covers the "0" initializer.
14956bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14957 SourceLocation EndLoc = InitRange.getEnd();
14958 if (EndLoc.isValid())
14959 Method->setRangeEnd(EndLoc);
14960
14961 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14962 Method->setPure();
14963 return false;
14964 }
14965
14966 if (!Method->isInvalidDecl())
14967 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14968 << Method->getDeclName() << InitRange;
14969 return true;
14970}
14971
14972void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14973 if (D->getFriendObjectKind())
14974 Diag(D->getLocation(), diag::err_pure_friend);
14975 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14976 CheckPureMethod(M, ZeroLoc);
14977 else
14978 Diag(D->getLocation(), diag::err_illegal_initializer);
14979}
14980
14981/// Determine whether the given declaration is a global variable or
14982/// static data member.
14983static bool isNonlocalVariable(const Decl *D) {
14984 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14985 return Var->hasGlobalStorage();
14986
14987 return false;
14988}
14989
14990/// Invoked when we are about to parse an initializer for the declaration
14991/// 'Dcl'.
14992///
14993/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14994/// static data member of class X, names should be looked up in the scope of
14995/// class X. If the declaration had a scope specifier, a scope will have
14996/// been created and passed in for this purpose. Otherwise, S will be null.
14997void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14998 // If there is no declaration, there was an error parsing it.
14999 if (!D || D->isInvalidDecl())
15000 return;
15001
15002 // We will always have a nested name specifier here, but this declaration
15003 // might not be out of line if the specifier names the current namespace:
15004 // extern int n;
15005 // int ::n = 0;
15006 if (S && D->isOutOfLine())
15007 EnterDeclaratorContext(S, D->getDeclContext());
15008
15009 // If we are parsing the initializer for a static data member, push a
15010 // new expression evaluation context that is associated with this static
15011 // data member.
15012 if (isNonlocalVariable(D))
15013 PushExpressionEvaluationContext(
15014 ExpressionEvaluationContext::PotentiallyEvaluated, D);
15015}
15016
15017/// Invoked after we are finished parsing an initializer for the declaration D.
15018void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15019 // If there is no declaration, there was an error parsing it.
15020 if (!D || D->isInvalidDecl())
15021 return;
15022
15023 if (isNonlocalVariable(D))
15024 PopExpressionEvaluationContext();
15025
15026 if (S && D->isOutOfLine())
15027 ExitDeclaratorContext(S);
15028}
15029
15030/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15031/// C++ if/switch/while/for statement.
15032/// e.g: "if (int x = f()) {...}"
15033DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15034 // C++ 6.4p2:
15035 // The declarator shall not specify a function or an array.
15036 // The type-specifier-seq shall not contain typedef and shall not declare a
15037 // new class or enumeration.
15038 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15039 "Parser allowed 'typedef' as storage class of condition decl.");
15040
15041 Decl *Dcl = ActOnDeclarator(S, D);
15042 if (!Dcl)
15043 return true;
15044
15045 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15046 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15047 << D.getSourceRange();
15048 return true;
15049 }
15050
15051 return Dcl;
15052}
15053
15054void Sema::LoadExternalVTableUses() {
15055 if (!ExternalSource)
15056 return;
15057
15058 SmallVector<ExternalVTableUse, 4> VTables;
15059 ExternalSource->ReadUsedVTables(VTables);
15060 SmallVector<VTableUse, 4> NewUses;
15061 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15062 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15063 = VTablesUsed.find(VTables[I].Record);
15064 // Even if a definition wasn't required before, it may be required now.
15065 if (Pos != VTablesUsed.end()) {
15066 if (!Pos->second && VTables[I].DefinitionRequired)
15067 Pos->second = true;
15068 continue;
15069 }
15070
15071 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15072 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15073 }
15074
15075 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15076}
15077
15078void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15079 bool DefinitionRequired) {
15080 // Ignore any vtable uses in unevaluated operands or for classes that do
15081 // not have a vtable.
15082 if (!Class->isDynamicClass() || Class->isDependentContext() ||
15083 CurContext->isDependentContext() || isUnevaluatedContext())
15084 return;
15085 // Do not mark as used if compiling for the device outside of the target
15086 // region.
15087 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15088 !isInOpenMPDeclareTargetContext() &&
15089 !isInOpenMPTargetExecutionDirective()) {
15090 if (!DefinitionRequired)
15091 MarkVirtualMembersReferenced(Loc, Class);
15092 return;
15093 }
15094
15095 // Try to insert this class into the map.
15096 LoadExternalVTableUses();
15097 Class = Class->getCanonicalDecl();
15098 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15099 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15100 if (!Pos.second) {
15101 // If we already had an entry, check to see if we are promoting this vtable
15102 // to require a definition. If so, we need to reappend to the VTableUses
15103 // list, since we may have already processed the first entry.
15104 if (DefinitionRequired && !Pos.first->second) {
15105 Pos.first->second = true;
15106 } else {
15107 // Otherwise, we can early exit.
15108 return;
15109 }
15110 } else {
15111 // The Microsoft ABI requires that we perform the destructor body
15112 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15113 // the deleting destructor is emitted with the vtable, not with the
15114 // destructor definition as in the Itanium ABI.
15115 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15116 CXXDestructorDecl *DD = Class->getDestructor();
15117 if (DD && DD->isVirtual() && !DD->isDeleted()) {
15118 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15119 // If this is an out-of-line declaration, marking it referenced will
15120 // not do anything. Manually call CheckDestructor to look up operator
15121 // delete().
15122 ContextRAII SavedContext(*this, DD);
15123 CheckDestructor(DD);
15124 } else {
15125 MarkFunctionReferenced(Loc, Class->getDestructor());
15126 }
15127 }
15128 }
15129 }
15130
15131 // Local classes need to have their virtual members marked
15132 // immediately. For all other classes, we mark their virtual members
15133 // at the end of the translation unit.
15134 if (Class->isLocalClass())
15135 MarkVirtualMembersReferenced(Loc, Class);
15136 else
15137 VTableUses.push_back(std::make_pair(Class, Loc));
15138}
15139
15140bool Sema::DefineUsedVTables() {
15141 LoadExternalVTableUses();
15142 if (VTableUses.empty())
15143 return false;
15144
15145 // Note: The VTableUses vector could grow as a result of marking
15146 // the members of a class as "used", so we check the size each
15147 // time through the loop and prefer indices (which are stable) to
15148 // iterators (which are not).
15149 bool DefinedAnything = false;
15150 for (unsigned I = 0; I != VTableUses.size(); ++I) {
15151 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15152 if (!Class)
15153 continue;
15154 TemplateSpecializationKind ClassTSK =
15155 Class->getTemplateSpecializationKind();
15156
15157 SourceLocation Loc = VTableUses[I].second;
15158
15159 bool DefineVTable = true;
15160
15161 // If this class has a key function, but that key function is
15162 // defined in another translation unit, we don't need to emit the
15163 // vtable even though we're using it.
15164 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15165 if (KeyFunction && !KeyFunction->hasBody()) {
15166 // The key function is in another translation unit.
15167 DefineVTable = false;
15168 TemplateSpecializationKind TSK =
15169 KeyFunction->getTemplateSpecializationKind();
15170 assert(TSK != TSK_ExplicitInstantiationDefinition &&
15171 TSK != TSK_ImplicitInstantiation &&
15172 "Instantiations don't have key functions");
15173 (void)TSK;
15174 } else if (!KeyFunction) {
15175 // If we have a class with no key function that is the subject
15176 // of an explicit instantiation declaration, suppress the
15177 // vtable; it will live with the explicit instantiation
15178 // definition.
15179 bool IsExplicitInstantiationDeclaration =
15180 ClassTSK == TSK_ExplicitInstantiationDeclaration;
15181 for (auto R : Class->redecls()) {
15182 TemplateSpecializationKind TSK
15183 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15184 if (TSK == TSK_ExplicitInstantiationDeclaration)
15185 IsExplicitInstantiationDeclaration = true;
15186 else if (TSK == TSK_ExplicitInstantiationDefinition) {
15187 IsExplicitInstantiationDeclaration = false;
15188 break;
15189 }
15190 }
15191
15192 if (IsExplicitInstantiationDeclaration)
15193 DefineVTable = false;
15194 }
15195
15196 // The exception specifications for all virtual members may be needed even
15197 // if we are not providing an authoritative form of the vtable in this TU.
15198 // We may choose to emit it available_externally anyway.
15199 if (!DefineVTable) {
15200 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15201 continue;
15202 }
15203
15204 // Mark all of the virtual members of this class as referenced, so
15205 // that we can build a vtable. Then, tell the AST consumer that a
15206 // vtable for this class is required.
15207 DefinedAnything = true;
15208 MarkVirtualMembersReferenced(Loc, Class);
15209 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15210 if (VTablesUsed[Canonical])
15211 Consumer.HandleVTable(Class);
15212
15213 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15214 // no key function or the key function is inlined. Don't warn in C++ ABIs
15215 // that lack key functions, since the user won't be able to make one.
15216 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15217 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15218 const FunctionDecl *KeyFunctionDef = nullptr;
15219 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15220 KeyFunctionDef->isInlined())) {
15221 Diag(Class->getLocation(),
15222 ClassTSK == TSK_ExplicitInstantiationDefinition
15223 ? diag::warn_weak_template_vtable
15224 : diag::warn_weak_vtable)
15225 << Class;
15226 }
15227 }
15228 }
15229 VTableUses.clear();
15230
15231 return DefinedAnything;
15232}
15233
15234void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15235 const CXXRecordDecl *RD) {
15236 for (const auto *I : RD->methods())
15237 if (I->isVirtual() && !I->isPure())
15238 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15239}
15240
15241void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15242 const CXXRecordDecl *RD,
15243 bool ConstexprOnly) {
15244 // Mark all functions which will appear in RD's vtable as used.
15245 CXXFinalOverriderMap FinalOverriders;
15246 RD->getFinalOverriders(FinalOverriders);
15247 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15248 E = FinalOverriders.end();
15249 I != E; ++I) {
15250 for (OverridingMethods::const_iterator OI = I->second.begin(),
15251 OE = I->second.end();
15252 OI != OE; ++OI) {
15253 assert(OI->second.size() > 0 && "no final overrider");
15254 CXXMethodDecl *Overrider = OI->second.front().Method;
15255
15256 // C++ [basic.def.odr]p2:
15257 // [...] A virtual member function is used if it is not pure. [...]
15258 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15259 MarkFunctionReferenced(Loc, Overrider);
15260 }
15261 }
15262
15263 // Only classes that have virtual bases need a VTT.
15264 if (RD->getNumVBases() == 0)
15265 return;
15266
15267 for (const auto &I : RD->bases()) {
15268 const CXXRecordDecl *Base =
15269 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15270 if (Base->getNumVBases() == 0)
15271 continue;
15272 MarkVirtualMembersReferenced(Loc, Base);
15273 }
15274}
15275
15276/// SetIvarInitializers - This routine builds initialization ASTs for the
15277/// Objective-C implementation whose ivars need be initialized.
15278void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15279 if (!getLangOpts().CPlusPlus)
15280 return;
15281 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15282 SmallVector<ObjCIvarDecl*, 8> ivars;
15283 CollectIvarsToConstructOrDestruct(OID, ivars);
15284 if (ivars.empty())
15285 return;
15286 SmallVector<CXXCtorInitializer*, 32> AllToInit;
15287 for (unsigned i = 0; i < ivars.size(); i++) {
15288 FieldDecl *Field = ivars[i];
15289 if (Field->isInvalidDecl())
15290 continue;
15291
15292 CXXCtorInitializer *Member;
15293 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15294 InitializationKind InitKind =
15295 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15296
15297 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15298 ExprResult MemberInit =
15299 InitSeq.Perform(*this, InitEntity, InitKind, None);
15300 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15301 // Note, MemberInit could actually come back empty if no initialization
15302 // is required (e.g., because it would call a trivial default constructor)
15303 if (!MemberInit.get() || MemberInit.isInvalid())
15304 continue;
15305
15306 Member =
15307 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15308 SourceLocation(),
15309 MemberInit.getAs<Expr>(),
15310 SourceLocation());
15311 AllToInit.push_back(Member);
15312
15313 // Be sure that the destructor is accessible and is marked as referenced.
15314 if (const RecordType *RecordTy =
15315 Context.getBaseElementType(Field->getType())
15316 ->getAs<RecordType>()) {
15317 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15318 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15319 MarkFunctionReferenced(Field->getLocation(), Destructor);
15320 CheckDestructorAccess(Field->getLocation(), Destructor,
15321 PDiag(diag::err_access_dtor_ivar)
15322 << Context.getBaseElementType(Field->getType()));
15323 }
15324 }
15325 }
15326 ObjCImplementation->setIvarInitializers(Context,
15327 AllToInit.data(), AllToInit.size());
15328 }
15329}
15330
15331static
15332void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15333 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15334 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15335 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15336 Sema &S) {
15337 if (Ctor->isInvalidDecl())
15338 return;
15339
15340 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15341
15342 // Target may not be determinable yet, for instance if this is a dependent
15343 // call in an uninstantiated template.
15344 if (Target) {
15345 const FunctionDecl *FNTarget = nullptr;
15346 (void)Target->hasBody(FNTarget);
15347 Target = const_cast<CXXConstructorDecl*>(
15348 cast_or_null<CXXConstructorDecl>(FNTarget));
15349 }
15350
15351 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15352 // Avoid dereferencing a null pointer here.
15353 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15354
15355 if (!Current.insert(Canonical).second)
15356 return;
15357
15358 // We know that beyond here, we aren't chaining into a cycle.
15359 if (!Target || !Target->isDelegatingConstructor() ||
15360 Target->isInvalidDecl() || Valid.count(TCanonical)) {
15361 Valid.insert(Current.begin(), Current.end());
15362 Current.clear();
15363 // We've hit a cycle.
15364 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15365 Current.count(TCanonical)) {
15366 // If we haven't diagnosed this cycle yet, do so now.
15367 if (!Invalid.count(TCanonical)) {
15368 S.Diag((*Ctor->init_begin())->getSourceLocation(),
15369 diag::warn_delegating_ctor_cycle)
15370 << Ctor;
15371
15372 // Don't add a note for a function delegating directly to itself.
15373 if (TCanonical != Canonical)
15374 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15375
15376 CXXConstructorDecl *C = Target;
15377 while (C->getCanonicalDecl() != Canonical) {
15378 const FunctionDecl *FNTarget = nullptr;
15379 (void)C->getTargetConstructor()->hasBody(FNTarget);
15380 assert(FNTarget && "Ctor cycle through bodiless function");
15381
15382 C = const_cast<CXXConstructorDecl*>(
15383 cast<CXXConstructorDecl>(FNTarget));
15384 S.Diag(C->getLocation(), diag::note_which_delegates_to);
15385 }
15386 }
15387
15388 Invalid.insert(Current.begin(), Current.end());
15389 Current.clear();
15390 } else {
15391 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15392 }
15393}
15394
15395
15396void Sema::CheckDelegatingCtorCycles() {
15397 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15398
15399 for (DelegatingCtorDeclsType::iterator
15400 I = DelegatingCtorDecls.begin(ExternalSource),
15401 E = DelegatingCtorDecls.end();
15402 I != E; ++I)
15403 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15404
15405 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15406 (*CI)->setInvalidDecl();
15407}
15408
15409namespace {
15410 /// AST visitor that finds references to the 'this' expression.
15411 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15412 Sema &S;
15413
15414 public:
15415 explicit FindCXXThisExpr(Sema &S) : S(S) { }
15416
15417 bool VisitCXXThisExpr(CXXThisExpr *E) {
15418 S.Diag(E->getLocation(), diag::err_this_static_member_func)
15419 << E->isImplicit();
15420 return false;
15421 }
15422 };
15423}
15424
15425bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15426 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15427 if (!TSInfo)
15428 return false;
15429
15430 TypeLoc TL = TSInfo->getTypeLoc();
15431 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15432 if (!ProtoTL)
15433 return false;
15434
15435 // C++11 [expr.prim.general]p3:
15436 // [The expression this] shall not appear before the optional
15437 // cv-qualifier-seq and it shall not appear within the declaration of a
15438 // static member function (although its type and value category are defined
15439 // within a static member function as they are within a non-static member
15440 // function). [ Note: this is because declaration matching does not occur
15441 // until the complete declarator is known. - end note ]
15442 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15443 FindCXXThisExpr Finder(*this);
15444
15445 // If the return type came after the cv-qualifier-seq, check it now.
15446 if (Proto->hasTrailingReturn() &&
15447 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15448 return true;
15449
15450 // Check the exception specification.
15451 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15452 return true;
15453
15454 return checkThisInStaticMemberFunctionAttributes(Method);
15455}
15456
15457bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15458 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15459 if (!TSInfo)
15460 return false;
15461
15462 TypeLoc TL = TSInfo->getTypeLoc();
15463 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15464 if (!ProtoTL)
15465 return false;
15466
15467 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15468 FindCXXThisExpr Finder(*this);
15469
15470 switch (Proto->getExceptionSpecType()) {
15471 case EST_Unparsed:
15472 case EST_Uninstantiated:
15473 case EST_Unevaluated:
15474 case EST_BasicNoexcept:
15475 case EST_NoThrow:
15476 case EST_DynamicNone:
15477 case EST_MSAny:
15478 case EST_None:
15479 break;
15480
15481 case EST_DependentNoexcept:
15482 case EST_NoexceptFalse:
15483 case EST_NoexceptTrue:
15484 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15485 return true;
15486 LLVM_FALLTHROUGH;
15487
15488 case EST_Dynamic:
15489 for (const auto &E : Proto->exceptions()) {
15490 if (!Finder.TraverseType(E))
15491 return true;
15492 }
15493 break;
15494 }
15495
15496 return false;
15497}
15498
15499bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15500 FindCXXThisExpr Finder(*this);
15501
15502 // Check attributes.
15503 for (const auto *A : Method->attrs()) {
15504 // FIXME: This should be emitted by tblgen.
15505 Expr *Arg = nullptr;
15506 ArrayRef<Expr *> Args;
15507 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15508 Arg = G->getArg();
15509 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15510 Arg = G->getArg();
15511 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15512 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15513 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15514 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15515 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15516 Arg = ETLF->getSuccessValue();
15517 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15518 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15519 Arg = STLF->getSuccessValue();
15520 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15521 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15522 Arg = LR->getArg();
15523 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15524 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15525 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15526 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15527 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15528 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15529 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15530 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15531 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15532 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15533
15534 if (Arg && !Finder.TraverseStmt(Arg))
15535 return true;
15536
15537 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15538 if (!Finder.TraverseStmt(Args[I]))
15539 return true;
15540 }
15541 }
15542
15543 return false;
15544}
15545
15546void Sema::checkExceptionSpecification(
15547 bool IsTopLevel, ExceptionSpecificationType EST,
15548 ArrayRef<ParsedType> DynamicExceptions,
15549 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15550 SmallVectorImpl<QualType> &Exceptions,
15551 FunctionProtoType::ExceptionSpecInfo &ESI) {
15552 Exceptions.clear();
15553 ESI.Type = EST;
15554 if (EST == EST_Dynamic) {
15555 Exceptions.reserve(DynamicExceptions.size());
15556 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15557 // FIXME: Preserve type source info.
15558 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15559
15560 if (IsTopLevel) {
15561 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15562 collectUnexpandedParameterPacks(ET, Unexpanded);
15563 if (!Unexpanded.empty()) {
15564 DiagnoseUnexpandedParameterPacks(
15565 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15566 Unexpanded);
15567 continue;
15568 }
15569 }
15570
15571 // Check that the type is valid for an exception spec, and
15572 // drop it if not.
15573 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15574 Exceptions.push_back(ET);
15575 }
15576 ESI.Exceptions = Exceptions;
15577 return;
15578 }
15579
15580 if (isComputedNoexcept(EST)) {
15581 assert((NoexceptExpr->isTypeDependent() ||
15582 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15583 Context.BoolTy) &&
15584 "Parser should have made sure that the expression is boolean");
15585 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15586 ESI.Type = EST_BasicNoexcept;
15587 return;
15588 }
15589
15590 ESI.NoexceptExpr = NoexceptExpr;
15591 return;
15592 }
15593}
15594
15595void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15596 ExceptionSpecificationType EST,
15597 SourceRange SpecificationRange,
15598 ArrayRef<ParsedType> DynamicExceptions,
15599 ArrayRef<SourceRange> DynamicExceptionRanges,
15600 Expr *NoexceptExpr) {
15601 if (!MethodD)
15602 return;
15603
15604 // Dig out the method we're referring to.
15605 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15606 MethodD = FunTmpl->getTemplatedDecl();
15607
15608 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15609 if (!Method)
15610 return;
15611
15612 // Check the exception specification.
15613 llvm::SmallVector<QualType, 4> Exceptions;
15614 FunctionProtoType::ExceptionSpecInfo ESI;
15615 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15616 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15617 ESI);
15618
15619 // Update the exception specification on the function type.
15620 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15621
15622 if (Method->isStatic())
15623 checkThisInStaticMemberFunctionExceptionSpec(Method);
15624
15625 if (Method->isVirtual()) {
15626 // Check overrides, which we previously had to delay.
15627 for (const CXXMethodDecl *O : Method->overridden_methods())
15628 CheckOverridingFunctionExceptionSpec(Method, O);
15629 }
15630}
15631
15632/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15633///
15634MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15635 SourceLocation DeclStart, Declarator &D,
15636 Expr *BitWidth,
15637 InClassInitStyle InitStyle,
15638 AccessSpecifier AS,
15639 const ParsedAttr &MSPropertyAttr) {
15640 IdentifierInfo *II = D.getIdentifier();
15641 if (!II) {
15642 Diag(DeclStart, diag::err_anonymous_property);
15643 return nullptr;
15644 }
15645 SourceLocation Loc = D.getIdentifierLoc();
15646
15647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15648 QualType T = TInfo->getType();
15649 if (getLangOpts().CPlusPlus) {
15650 CheckExtraCXXDefaultArguments(D);
15651
15652 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15653 UPPC_DataMemberType)) {
15654 D.setInvalidType();
15655 T = Context.IntTy;
15656 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15657 }
15658 }
15659
15660 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15661
15662 if (D.getDeclSpec().isInlineSpecified())
15663 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15664 << getLangOpts().CPlusPlus17;
15665 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15666 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15667 diag::err_invalid_thread)
15668 << DeclSpec::getSpecifierName(TSCS);
15669
15670 // Check to see if this name was declared as a member previously
15671 NamedDecl *PrevDecl = nullptr;
15672 LookupResult Previous(*this, II, Loc, LookupMemberName,
15673 ForVisibleRedeclaration);
15674 LookupName(Previous, S);
15675 switch (Previous.getResultKind()) {
15676 case LookupResult::Found:
15677 case LookupResult::FoundUnresolvedValue:
15678 PrevDecl = Previous.getAsSingle<NamedDecl>();
15679 break;
15680
15681 case LookupResult::FoundOverloaded:
15682 PrevDecl = Previous.getRepresentativeDecl();
15683 break;
15684
15685 case LookupResult::NotFound:
15686 case LookupResult::NotFoundInCurrentInstantiation:
15687 case LookupResult::Ambiguous:
15688 break;
15689 }
15690
15691 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15692 // Maybe we will complain about the shadowed template parameter.
15693 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15694 // Just pretend that we didn't see the previous declaration.
15695 PrevDecl = nullptr;
15696 }
15697
15698 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15699 PrevDecl = nullptr;
15700
15701 SourceLocation TSSL = D.getBeginLoc();
15702 MSPropertyDecl *NewPD =
15703 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15704 MSPropertyAttr.getPropertyDataGetter(),
15705 MSPropertyAttr.getPropertyDataSetter());
15706 ProcessDeclAttributes(TUScope, NewPD, D);
15707 NewPD->setAccess(AS);
15708
15709 if (NewPD->isInvalidDecl())
15710 Record->setInvalidDecl();
15711
15712 if (D.getDeclSpec().isModulePrivateSpecified())
15713 NewPD->setModulePrivate();
15714
15715 if (NewPD->isInvalidDecl() && PrevDecl) {
15716 // Don't introduce NewFD into scope; there's already something
15717 // with the same name in the same scope.
15718 } else if (II) {
15719 PushOnScopeChains(NewPD, S);
15720 } else
15721 Record->addDecl(NewPD);
15722
15723 return NewPD;
15724}
15725